Given a certain string, e.g., s = "tesX123"
, how can I replace a certain character at a certain location?
In this example, the character at position 4
should be changed to "t"
.
Does a method exist in the style of setChar(s, 4, "t")
which would result in test123
?
String are immutable in Java. You can't change them. You need to create a new string with the character replaced.
replace() method helps to replace the occurrence of the given old character with the new character or substring. The method contains the parameters like old(a character that you wish to replace), new(a new character you would like to replace with), and count(a number of times you want to replace the character).
Like StringBuilder, the StringBuffer class has a predefined method for this purpose – setCharAt(). Replace the character at the specific index by calling this method and passing the character and the index as the parameter.
The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.
Try substr()
substr(s, 4, 4) <- "t"
> s
#[1] "test123"
We can use sub
sub("(.{3}).", "\\1t", s)
#[1] "test123"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With