Replace a specific Substring?

Inman

Well-Known Member
Licensed User
Longtime User
I know we can replace a part of the string using string.replace() but that will replace all occurrences. I want to replace only the 2nd occurrence and keep the rest of the string untouched. How can I do that?
 

Mahares

Expert
Licensed User
Longtime User
I hope this function with its example will do what you are looking for:

B4X:
Sub Replace(strVar As String,strToReplace As String,strReplacement As String,Position As Int) As String
   Dim strArray() As String
   strArray=Regex.Split(strToReplace,strVar)
   Dim Mystr As String
   For i=0 To strArray.Length-1
     If i=Position Then  'replace the position occurence
          Mystr=Mystr & strArray(i) & strReplacement   
      Else
         Mystr=Mystr & strArray(i) & strToReplace
      End If
   Next
   Return Mystr.SubString2(0,Mystr.Length-strToReplace.Length)
End Sub

B4X:
Msgbox(Replace("this forum is helpful for this case and this example","this","the other",1),"")
'Returns: this forum is helpful for the other case and this example
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
My version:
B4X:
Sub Activity_Create(FirstTime As Boolean)
   Log(Replace("abc abc abc abc", "abc", "def", 0))
   Log(Replace("abc abc abc abc", "abc", "def", 1))
   Log(Replace("abc abc abc abc", "abc", "def", 2))
   Log(Replace("abc abc abc abc", "abc", "def", 3))
   Log(Replace("abc abc abc abc", "abc", "def", 4))
End Sub

Sub Replace(OriginalString As String, Target As String, _
      Replacement As String, Ordinal As Int) As String
   Dim i As Int = -1
   For o = 0 To Ordinal
      i = OriginalString.IndexOf2(Target, i + 1)
      If i = -1 Then Return OriginalString
   Next
   Return OriginalString.SubString2(0, i) & Replacement & _
      OriginalString.SubString(i + Target.Length)
End Sub
Note that the first Ordinal is 0.
 
Upvote 0
Top