replace a character at a specific index in a string

replace a character at a specific index in a string  using -'java,string,replace,indexing,character'

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?

asked Sep 10, 2015 by Ive42O
0 votes

6 Answers

0 votes

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');

answered Sep 10, 2015 by KiaPapathan
0 votes

String is an immutable class in java any methods which seem to modify it always return a new string object with modification. if you want to manipulate a string consider StringBuilder or StringBuffer in case you require thread safety

answered Sep 10, 2015 by HueMoris
0 votes

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);
answered Sep 10, 2015 by Mau54U
0 votes

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.

answered Sep 10, 2015 by CarEhrhart
0 votes

I agree with Petar Ivanov but it is best if we implement in following way:

public String replace(String str, int index, char replace){     
        return str;
    }else if(index<0 || index>=str.length()){
        return str;
    char[] chars = str.toCharArray();
    chars[index] = replace;
    return String.valueOf(chars);       
answered Sep 10, 2015 by RoxieSheahan
0 votes

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.

answered Sep 10, 2015 by GKDSiobhanu