fxm wrote: ↑Sep 16, 2022 6:14 An nth version in pure FreeBASIC!
But compatible with zstring and string (supports null character).Code: Select all
Sub split(Byref s1 As String, Byref s2 As String, splits(Any) As String) Dim As Integer n, n0 = 1 Do Redim Preserve splits(Ubound(splits) + 1) n = Instr(n0, s1, s2) If n > 0 Then splits(Ubound(splits)) = Mid(s1, n0, n - n0) n0 = n + Len(s2) Else splits(Ubound(splits)) = Mid(s1, n0) Exit Do End If Loop End Sub Dim As String s1 = "reinvent the wheel " & Chr(0) & " in pure FreeBASIC :lol:" Dim As String splits(Any) Print s1 Print split(s1, " ", splits()) For i As Integer = 0 To Ubound(splits) Print i & " '" & splits(i) & "'" Next i Sleep
Improved version of the previous 'split(Byref s1 As String, Byref s2 As String, splits(Any) As String)' subroutine above, to minimize execution time:
- The 'splits()' array is first resized to a maximum size depending to 'Len(s1) / Len(s2) + 1', then resized at the end to the true useful size.
- 'Mid(s1, ...)' is no longer used. Instead the descriptor of 's1' is temporary modified to match to the 'Mid(s1, ...)' string used previously.
- A non-empty string array passed as an argument is also supported, and the array is only completed (with the extracted sub-strings).
Code: Select all
Sub split(Byref s1 As String, Byref s2 As String, splits(Any) As String)
Type SD
Dim As Any Ptr p
Dim As Integer l
End Type
Dim As SD Ptr psd1 = Cptr(SD Ptr, @s1)
Dim As Any Ptr p1 = psd1->p
Dim As Integer l1 = psd1->l
Dim As integer i = Ubound(splits) + 1
Redim Preserve splits(Lbound(splits) To Ubound(Splits) + Len(s1) / Len(s2) + 1)
Dim As Integer n, n0 = 1
Do
n = Instr(n0, s1, s2)
psd1->p = p1 + n0 - 1
If n > 0 Then
psd1->l = n - n0
splits(i) = s1
psd1->p = p1
psd1->l = l1
n0 = n + Len(s2)
Else
psd1->l = l1 - n0 + 1
splits(i) = s1
psd1->p = p1
psd1->l = l1
Redim Preserve splits(Lbound(splits) To i)
Exit Do
End If
i += 1
Loop
End Sub
Dim As String s1 = "reinvent the wheel " & Chr(0) & " in optimized pure FreeBASIC :lol:"
Dim As String splits(Any)
Print s1
Print
split(s1, " ", splits())
For i As Integer = 0 To Ubound(splits)
Print i & " '" & splits(i) & "'"
Next i
Sleep