Date: 02-16-2022
Return to Index
Function PBMain() As Long
created by gbSnippets
Local Index As Long, D$, R$, Full$
Index = 1 'substring to be acted on
Full$ = "abc:1234:rs:t122:abcdefgh:adfdafs" 'full string
D$ = ":" 'delimiter
R$ = ":----" 'new value of substring
'show position of nth substring (n=Index)
? "Delimiter #" + Trim$(Str$(Index)) + " found at position " + Str$(DPos(Full$,Index,D$)) + $CrLf + $CrLf + Full$
'replace nth substring
ReplaceSS(Full$,4,D$,R$) 'source, nth substring, delimiter, newstring
?Full$
End Function
Function DPos(Full$,Index As Long,D$) As Long
Local i,iPos,iCount As Long
iPos = InStr(Full$,D$)
While iPos
Incr iCount
If iCount = Index Then Function = iPos : Exit Function
iPos = InStr(iPos+1,Full$,D$)
Wend
End Function
Sub ReplaceSS(FullString$, Index As Long, D$, NewElement$)
Local iPosA, iPosB As Long
iPosA = DPos(FullString$,Index,D$) 'start of n substring
iPosB = DPos(FullString$,Index+1,D$) 'start of (n+1) substring
If iPosA = 0 Then Exit Sub 'no delimiter found, take not action
If iPosB = 0 Then iPosB = Len(FullString$) 'Index was last delimiter, so use all of FullString to the right
FullString$ = Left$(FullString$,iPosA-1) + NewElement$ + Mid$(FullString$,iPosB)
End Sub
ReDim tempArray(1 To ParseCount(FullString$,Delimiter$)) 'size a temp array to hold the subelements
Parse FullString$, tempArray(), Delimiter$ 'split the full string into subelements
tempArray(Index) = NewString$ 'replace the index element
FullString$ = Join$(tempArray(),Delimiter) 'rebuild the full stri
Sub ReplaceElement(FulLString$,NewString$,Delimiter$)
iCount = ParseCount(FullString$, Delimiter$)
If iCount = 0 Then FullString$ = NewString$ : Exit Sub
ReDim tempArray(1 To iCount) 'size a temp array to hold the subelements
Parse FullString$, tempArray(), Delimiter$ 'split the full string into subelements
tempArray(Index) = NewString$ 'replace the index element
FullString$ = Join$(tempArray(),Delimiter) 'rebuild the full stri
End Sub
http://www.garybeene.com/sw/gbsnippets.htm