News:

Welcome to RetroCoders Community

Main Menu

split word from string text function

Started by ron77, May 31, 2022, 07:06 AM

Previous topic - Next topic

ron77

function Split(Text As String, Delim As String = " ", Count As Long = (1 shl 31)-1, Ret() As string) as long
    if Count<0 then Count = (1 shl 31)-1 'max possible
  if Count=0 then erase ret: return 0
  
  dim as long iStart = 1
  for N as long = 0 to Count-1
    redim preserve Ret(N) as string
    var iFound = instr( iStart , Text , Delim )
    if iFound=0 then Ret(N) = mid(Text,iStart): return N+1
    Ret(N) = mid(Text,iStart,(iFound-iStart))
    if iFound=iStart then N -= 1
    iStart = iFound+len(Delim)
  next N  
  return Count
End function
 
#define ShowResult() print iWords;: for N as integer = 0 to iWords-1 : print " '"+Words(N)+"'"; : next N : print
 
redim as string Words()
dim as integer iWords
 
iWords = Split("Hello World"," ",,Words())
ShowResult()
 
iWords = Split(" "," ",,Words())
ShowResult()
 
iWords = Split("Hello How are you"," ",2,Words())
ShowResult()
 
iWords = Split("Hello How are you"," H",,Words())
ShowResult()
 
iWords = Split("Hello How are you","!",,Words())
ShowResult()
 
sleep
 
 

__blackjack__

This doesn't need to be a function returning the length of the result array because that information can be queried from the result array with UBound().
,,Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." —Brian W. Kernighan