I'm trying to replace a character at a specific index in a string.
What I'm doing is:
String myName = "domanokz"; myName.charAt(4) = 'x';
This gives an error. Is there any method to do this?
Using 'str.replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.
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).
String are immutable in Java. You can't change them.
You need to create a new string with the character replaced.
String myName = "domanokz"; String newName = myName.substring(0,4)+'x'+myName.substring(5);
Or you can use a StringBuilder:
StringBuilder myName = new StringBuilder("domanokz"); myName.setCharAt(4, 'x'); System.out.println(myName);
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