Android Question Character replacement within a string

FERNANDO SILVEIRA

Active Member
Licensed User
Hello Guys,

Is there a way to execute a string.replace() on a given position of the string?
Let's say I have the string "FERNANDO" and want to replace the second "N" with "*" what would I do?

B4X:
dim wWord as string = "FERNANDO"
dim wNewWord as string = wWord.replace("N", "*")
log(wWord & " = " & wNewWord)

As far as I know, string.replace() replaces all occurrences of the substring, resulting "FER*A*DO" instead of "FERNA*DO".

Regards,
Fernando
 

Addo

Well-Known Member
Licensed User
you can use the following snippets

B4X:
str = "FERNANDO"
str = StrReplaceAt(str,5, "*")


Sub StrReplaceAt(str As String, Index As Int, Replacement As String) As String
    Dim newStr As String = str.SubString2(0, Index) & Replacement
    If Index < str.Length - 1 Then newStr = newStr & str.SubString(Index + 1)
    Return newStr
End Sub
 
Upvote 0

Derek Johnson

Active Member
Licensed User
Longtime User
Is there a way to execute a string.replace() on a given position of the string?

This bit of code should work:

B4X:
'Replace the Nth occurence of OldValue with NewValue
Sub ReplaceNth(Target As String, N As Int, OldValue As String, NewValue As String) As String
    Dim  I As Int, Posn As Int, Res As String
    Posn=0
    For I=1 To N
        Posn=Target.IndexOf2(OldValue,Posn)
        If Posn=-1 Then Return Target
        If I=N Then
            Res=Target.SubString2(0,Posn) & NewValue & Target.SubString(Posn+OldValue.Length)
        Else
            Posn=Posn+OldValue.length
        End If
    Next
    Return Res
End Sub

There is probably some solution using regular expressions too!

NB Just spotted reply by previous poster. The above routine is slightly more general and finds the Nth count of a potentially multi-character string with another potentially multi-character string. It depends on what exactly the requirement is of course.


Derek
 
Last edited:
Upvote 0
Top