String.ReplaceAt

  1. 2 weeks ago

    Dale A

    May 18 San Diego, California, USA

    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.

    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.

  2. Stefan C

    May 18 Testers

    Split the string by "fourth"
    rebuld the string

  3. Kem T

    May 18 Testers, Xojo Pro, XDC Speakers, MVP Answer Connecticut
    Edited 2 weeks ago
    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.

  4. Paul L

    May 18 Xojo Inc, Third Party Store

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

    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
  5. Markus R

    May 18 Testers, Xojo Pro Europe / Germany / Lower Saxon...
    Edited 2 weeks ago

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

  6. Dale A

    May 19 San Diego, California, USA

    @Kem T 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.

    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.

or Sign Up to reply!