String.ReplaceAt

I have a need to replace a portion of a string with another string when there may be more than one instance of the target string in the original string. For example, I may have a string like “The fourth hour of the fourth day of the fourth month of the fourth season…” and I want to replace the second “fourth” with “fifth” so that the resulting string is “The fourth hour of the fifth day of the fourth month of the fourth season…” Currently, I have to laboriously parse and separate the string and rebuild it.

With all of the String.Replace… methods in Xojo, what I would really like is a String.ReplaceAt method that takes a ‘findString’, a ‘replaceString’, and an ‘instance’ integer.

Split the string by “fourth”
rebuld the string

dim rx as new RegEx
rx.SearchPattern = "(?Umsi)((?:.*fourth){1})(.*)fourth"
rx.ReplacementPattern = "$1$2fifth"

dim replacedText as string = rx.Replace( sourceText )

The {1} says, “skip the first occurrence”, so if you want to change the x occurrence, change that to x-1.

Another option is RegEx. The RegEx.Replace page has sample code that does this:

[code]Var re As New RegEx
re.SearchPattern = “\bfourth\b”
re.ReplacementPattern = “fifth”

Var sampleText As String = “The fourth hour of the fourth day of the fourth month of the fourth season…”

Var match As RegExMatch = re.Search(sampleText) // find first SearchPattern in text
If match <> Nil Then
sampleText = re.Replace // Find the next SearchPattern in the text and replace it
End If[/code]

missing is Mid(“Hello”,1,1)=“ABC”
it was useful in VB6

[quote=489156:@Kem Tekinay][code]
dim rx as new RegEx
rx.SearchPattern = “(?Umsi)((?:.fourth){1})(.)fourth”
rx.ReplacementPattern = “$1$2fifth”

dim replacedText as string = rx.Replace( sourceText )
[/code]

The {1} says, “skip the first occurrence”, so if you want to change the x occurrence, change that to x-1.[/quote]
Very nice. Not the approach I used, Kem, since I am not very adept at RegEx but it is definitely going into my tools module.