Android Question Replace character at position X

wonder

Expert
Licensed User
Longtime User
Maybe I'm missing something...

Let's say I have a random string.
B4X:
Dim str = "asdasdhjkahdkjahdkjashd" As String
I want to replace the 5th character with "0".

str.CharAt(4) = "0" doesn't work...

str.Replace(CharAt(4), "0") wouldn't work either, as it would replace every "s".
 

MikeH

Well-Known Member
Licensed User
Longtime User
str = str.substring2(0,3) & newChar & str.substring(5)
 
Upvote 0

RandomCoder

Well-Known Member
Licensed User
Longtime User
I was just about to reply with the same as @MikeH although I think that the 3 should really be a 4.
CharAt is a read-only method.
 
Upvote 0

MikeH

Well-Known Member
Licensed User
Longtime User
I was just about to reply with the same as @MikeH although I think that the 3 should really be a 4.
CharAt is a read-only method.

Yes, its late and Im tired after a solid day of coding. I edited those numbers at least twice ;)
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Strings are immutable. You cannot replace a character. You can create a new string based on the previous one:

B4X:
Dim s As String = "abcdef"
s = StrReplaceAt(s, 2, "X")

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
Top