Android Question String replace first

KZero

Active Member
Licensed User
Longtime User
Hello,

how i can replace only the first occurrence in the string
because the regular "string.replace" replaces all instances

i think there is a way with "regex.replace2" but i didn't find any example

thanks in advance
 

derez

Expert
Licensed User
Longtime User
string.IndexOf(SearchFor as string) will give you the index of first occurrence of the argument in the string, then you can use substring to manipulate it.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
B4X:
Log(ReplaceFirst("3434abc abd",   "434", "dddd"))

Sub ReplaceFirst(s As String, SearchFor As String, ReplaceWith As String) As String
   Dim i As Int = s.IndexOf(SearchFor)
   If i > -1 Then
     Return s.SubString2(0, i) & ReplaceWith & s.SubString(i + SearchFor.Length)
   Else
     Return s
   End If
End Sub
 
Upvote 0
Top