Page 1 of 1

ParseString & SplitString

Posted: Sun Jun 30, 2024 7:24 pm
by RSrole
Powerbasic has a very useful function called Parse$. Here's my version in Purebasic
s$ is the string to scan, d$ is the delimiter string and p is the position in s$. First position is 1

Code: Select all

Procedure.s ParseString(s$,d$,p)
  If p < 1:ProcedureReturn s$:EndIf
  If Len(s$) = 0:ProcedureReturn "":EndIf
  If Len(d$) = 0:ProcedureReturn s$:EndIf
  If p > CountString(s$,d$):ProcedureReturn "":EndIf
  
  Protected last,Position,i = 1
  Repeat
    Last = Position
    Position = FindString(s$ , d$, Position + 1)
    If Position > 0
      If i = p
        If last = 0
          ProcedureReturn Left(s$,Position-1)
        Else
          ProcedureReturn Mid(s$,last + 1, Position-last)
        EndIf
      EndIf
    EndIf
    i = i + 1
  Until Not Position  
  ProcedureReturn ""
EndProcedure
c# has a useful method called Split. Here's my Purebasic version:
s$ is the string to scan, d$ is the delimiter string. You must define Splits$() (or whatever you want to call it) NewList Splits$() before calling SplitString

Code: Select all

Procedure SplitString(s$,d$,List Splits$())
  ClearList(Splits$())
  If Len(s$) = 0:ProcedureReturn:EndIf
  If Len(d$) = 0:ProcedureReturn:EndIf  
  Protected last,Position,i = 1
  Repeat
    Last = Position
    Position = FindString(S$ , d$, Position + 1)
    If Position > 0
      AddElement(Splits$())
      If last = 0
        Splits$() = Left(s$,Position-1)
      Else
        Splits$() = Mid(s$,last + 1, Position-last)
      EndIf
    EndIf
  Until Not Position    
  ResetList(Splits$())
EndProcedure
Any improvements are appreciated. Both are based on the example code in the Purebasic helpfile for FindString. Thanks to Fred or whoever wrote that code.

Re: ParseString & SplitString

Posted: Sun Jun 30, 2024 7:34 pm
by infratec
If ParseString() is needed? Look at StringField().

You can alos use StringField() for the SplitString() procedure.
But if you want speed, you need to work with pointers.

Re: ParseString & SplitString

Posted: Sun Jun 30, 2024 7:50 pm
by Quin
Here's an example of StringField, from the help file:

Code: Select all

  For k = 1 To 6
    Debug StringField("Hello I am a splitted string", k, " ")
  Next
Unfortunately, as Infratec mentioned, StringField is pitifully slow. You honestly probably won't notice unless your app is doing a bunch, but here are a couple solutions/workarounds:
https://www.purebasic.fr/english/viewto ... ld#p568905
https://www.purebasic.fr/english/viewto ... ld#p542372
HTH

Re: ParseString & SplitString

Posted: Sun Jun 30, 2024 8:47 pm
by RSrole
Quin,

Thanks, I hadn't noticed that function. For my purposes, it's fast enough

Re: ParseString & SplitString

Posted: Sun Jun 30, 2024 11:36 pm
by mk-soft

Re: ParseString & SplitString

Posted: Mon Jul 01, 2024 6:05 pm
by RSrole
Looks good!