Date: 02-16-2022
Return to Index
created by gbSnippets
'The PARSE statement is used to separate a string into an array, where
'each element is found between specified delimiters.
'Delimiters can be single characters, multi-character strings, or a list
'of delimiters.
'The problem is, that a string like "x x", with 3 spaces in the middle,
'does not parse to "x" and "x". The PowerBASIC PARSE function recognizes
'each delimiter as a source of an array element, resulting in this case in
'a max dimension of 4, not 2.
'Primary Code:
'I started a thread on this topic that grew without bounds! Lots of folks
'weighed in with various schemes. Here's the thread.
http://www.powerbasic.com/support/pbforums/showthread.php?t=41439
'There are several approaches. The first 3 examples are fairly simple
'code. The 4th example is significantly faster. See the above thread
'for other examples.
'Example #1
'Credit: John Gleason / Chris Holbrook
'This code assumes a delimiter of a space.
'Loops using 2^n work, except for the need for a Space$(3) line.
'With a loop max of 5, up to 11806 spaces.
For i = 5 to 1 Step -1
Replace Space$(2^i) With " " In temp$
Next i
Replace " " With " " In temp$
'Example #2
'Credit: Jeff Blakeney
While Instr(temp$, " ")
Replace " " With " " In temp$
Wend
'Example#3
'Credit: Jeff Blakeney
lPos = 1
Do
RegRepl "[ ]+" In temp$ With " " At lPos TO lPos, tmp$
Loop Until lPos = 0
'Example#4
'Credit: Tom Hanlin
Local sTestString as String, pIn As Byte PTR, pOut AS Byte PTR
pIn = StrPTR(sTestString)
pOut = pIn
Do Until @pIn = 0
@pOut = @pIn
Incr pIn
Incr pOut
If @pIn[-1] = 32 Then
Do While @pIn = 32
Incr pIn
Loop
End If
Loop
sTestString = Left$(sTestString, pOut-StrPTR(sTestString))
'Compilable Example: (Jose Includes)
'This example splits a string (numbers separated by commas), then uses JOIN$
'to combine them with $crlf and puts the result in a file. Notepad is used to open
'the result. Note the use of PARSECOUNT to determine how many elements PARSE
'will return.
#Compiler PBWin 9, PBWin 10
#Compile EXE
#Dim All
%Unicode=1
#Include "Win32API.inc"
Global hDlg As Dword
Function PBMain() As Long
Dialog New Pixels, 0, "Test Code",300,300,200,200, %WS_OverlappedWindow To hDlg
Control Add Button, hDlg, 100,"Push", 50,10,100,20
Dialog Show Modal hDlg Call DlgProc
End Function
CallBack Function DlgProc() As Long
If CB.Msg = %WM_Command AND CB.Ctl = 100 AND CB.Ctlmsg = %BN_Clicked Then
Local temp$, i As Long
temp$ = "x x"
For i = 5 to 1 Step -1
Replace Space$(2^i) With " " In temp$
Next i
Replace " " With " " In temp$
Dim D(ParseCount(temp$, " ")) As String
MsgBox Str$(UBound(D))
End If
End Function
'gbs_00333
'Date: 03-10-2012
http://www.garybeene.com/sw/gbsnippets.htm