Date: 02-16-2022
Return to Index
created by gbSnippets
'Finding the position of the nth occurrence of one string within another can be
'useful when parsing or replacing text.
'Primary Code
Function NthPosition(mainstring$, substring$, n&) As Long
'returns 0 is Nth position not found
Local iPos&, i As Long, iStart&
iStart& = 1
For i = 1 To n&
iPos& = Instr(iStart&, mainstring$, Substring$)
If iPos& = 0 Then Exit For
iStart& = iPos& + Len(SubString$)
Next i
Function = iPos&
End Function
'Compilable Example: (Jose Includes)
#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
Local iRes&, i As Long
If CB.Msg = %WM_Command AND CB.Ctl = 100 AND CB.Ctlmsg = %BN_Clicked Then
For i = 1 To 5
MsgBox "Position " + Str$(i) + ": " + Str$(NthPosition("12345123451234512345", "45", i))
Next i
End If
End Function
Function NthPosition(mainstring$, substring$, n&) As Long
'returns 0 is Nth position not found
Local iPos&, i As Long, iStart&
iStart& = 1
For i = 1 To n&
iPos& = Instr(iStart&, mainstring$, Substring$)
If iPos& = 0 Then Exit For
iStart& = iPos& + Len(SubString$)
Next i
Function = iPos&
End Function
'gbs_00239
'Date: 03-10-2012
http://www.garybeene.com/sw/gbsnippets.htm