Replace a character at a specific index in a string?

1,031,947

Solution 1

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

Solution 2

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

Solution 3

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.

Solution 4

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

Solution 5

As previously answered here, String instances are immutable. StringBuffer and StringBuilder are mutable and suitable for such a purpose whether you need to be thread safe or not.

There is however a way to modify a String but I would never recommend it because it is unsafe, unreliable and it can can be considered as cheating : you can use reflection to modify the inner char array the String object contains. Reflection allows you to access fields and methods that are normally hidden in the current scope (private methods or fields from another class...).

public static void main(String[] args) {
    String text = "This is a test";
    try {
        //String.value is the array of char (char[])
        //that contains the text of the String
        Field valueField = String.class.getDeclaredField("value");
        //String.value is a private variable so it must be set as accessible 
        //to read and/or to modify its value
        valueField.setAccessible(true);
        //now we get the array the String instance is actually using
        char[] value = (char[])valueField.get(text);
        //The 13rd character is the "s" of the word "Test"
        value[12]='x';
        //We display the string which should be "This is a text"
        System.out.println(text);
    } catch (NoSuchFieldException | SecurityException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}
Share:
1,031,947
kazinix
Author by

kazinix

Updated on July 18, 2022

Comments

  • kazinix
    kazinix almost 2 years

    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?

  • kazinix
    kazinix over 12 years
    Ah, you mean like the replace method which will not modify the string but will just return a new string?
  • kazinix
    kazinix over 12 years
    That's kinda complicated Mr.Petar. Is that the best way you to do it? Ah, I heard of StringBuilder before, does that make any difference? Will it give me an easier method?
  • kazinix
    kazinix almost 12 years
    and what makes your solution better?
  • Diabolus Infernalis
    Diabolus Infernalis over 11 years
    although i strongly detest this method of being allowed "editability" of other's work on this StackOverFlow site. thoroughly unfair :/
  • kazinix
    kazinix over 11 years
    Syntax error. And even if corrected, say I want to replace the first 'o' with 'x', the second 'o' will be replaced too.
  • Shripad Bhat
    Shripad Bhat over 8 years
    This will replace all character which is same as charAt 4.
  • C.Champagne
    C.Champagne over 8 years
    I haven't downvoted your answer but I must admit I have a problem with the term "overwrite" (though I think we agree on the concept behind). The object itself remains unchanged. You just make your variable reference another object. By the way it you be interesting to mention that you create at least four String instances in your example.
  • Dawood ibn Kareem
    Dawood ibn Kareem over 7 years
    Problem: myName.replace(myName.charAt(5),'x') will give you dxmanxkz, which is probably not what's required.
  • Dale
    Dale about 7 years
    Love this solution. I ended up changing the 3rd line to be myNameChars[index] = character.toCharArray()[0]; for simplification. Nice solution.
  • user924
    user924 over 5 years
    it looks much better than the other uglier one myName.substring(0,4)+'x'+myName.substring(5);
  • Ariel
    Ariel over 3 years
    Keep in mind this copies the String twice. It's probably faster to use the String concatenation version instead.
  • Dominicentek Gaming
    Dominicentek Gaming almost 3 years
    it handles unexpected values. Like null strings and out of bounds indexes.
  • konsumer
    konsumer almost 3 years
    It will give you "dxmanokz" as replace only replaces first occurrence, unless it's a regex. Still incorrect for the same reason, though.