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\';
First thing I should have noticed is that charAt
is a method and assigning value to it using equal sign won't do anything. If a string is immutable, charAt
method, to make change to the string object must receive an argument containing the new character. Unfortunately, string is immutable. To modify the string, I needed to use StringBuilder as suggested by Mr. Petar Ivanov.
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);
String
is an immutable class in java. Any method which seems to modify it always returns a new string object with modification.
If you want to manipulate a string, consider StringBuilder
or StringBuffer
in case you require thread safety.
Turn the String into a char[], replace the letter by index, then convert the array back into a String.
String myName = "domanokz";
char[] myNameChars = myName.toCharArray();
myNameChars[4] = 'x';
myName = String.valueOf(myNameChars);
You can overwrite a string, as follows:
String myName = "halftime";
myName = myName.substring(0,4)+'x'+myName.substring(5);
Note that the string myName
occurs on both lines, and on both sides of the second line.
Therefore, even though strings may technically be immutable, in practice, you can treat them as editable by overwriting them.
I agree with Petar Ivanov but it is best if we implement in following way:
public String replace(String str, int index, char replace){
if(str==null){
return str;
}else if(index<0 || index>=str.length()){
return str;
}
char[] chars = str.toCharArray();
chars[index] = replace;
return String.valueOf(chars);
}