470

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?

jww
  • 97,681
  • 90
  • 411
  • 885
kazinix
  • 28,987
  • 33
  • 107
  • 157
  • 13
    I realize this has been answered to death, but it's worth noting that it is _never_ allowed to assign the result of a function call in java. There are no such things as the references of C(?) and C++. – ApproachingDarknessFish Apr 14 '13 at 00:11
  • 1
    @ValekHalfHeart in VB, you use parenthesis to access index of an array, that may be the reason why I'm confused when I was starting in Java :D – kazinix Aug 13 '13 at 02:40
  • @ApproachingDarknessFish I am not sure what you mean by it's "never allowed to assign the result of a function call in java". Surely you can do `double r = Math.sin(3.14)`? How does it relate to this question? Thanks. – flow2k Oct 08 '17 at 22:07
  • 1
    @flow2k Oh jeez, old comment so I can't edit but that's a typo, it should say that "it is never allowed to assign ***to*** the result of a function call in Java". I.e. you can write "foo = bar();" but never "bar() = foo;". – ApproachingDarknessFish Oct 08 '17 at 22:26
  • Thanks for the clarification @ApproachingDarknessFish. I think it would be strange to assign something to the result of a function - are there languages that actually permit this? I wonder what the use case would be. – flow2k Oct 15 '17 at 19:56
  • @flow2k It happens in instance methods in C++, for example `std::vector vec(5); vec.at(4) = 7;` and if you use [] syntax it just calls an operator overload that does the same thing. – ApproachingDarknessFish Oct 16 '17 at 06:04

9 Answers9

685

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);
waldyr.ar
  • 14,424
  • 6
  • 33
  • 64
Petar Ivanov
  • 91,536
  • 11
  • 82
  • 95
  • 3
    Ah, you mean like the `replace` method which will not modify the string but will just return a new string? – kazinix Aug 05 '11 at 06:39
  • 1
    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 Aug 05 '11 at 06:41
214

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);
16dots
  • 2,941
  • 1
  • 13
  • 15
  • 1
    Love this solution. I ended up changing the 3rd line to be myNameChars[index] = character.toCharArray()[0]; for simplification. Nice solution. – Dale Mar 01 '17 at 21:22
  • 6
    it looks much better than the other uglier one `myName.substring(0,4)+'x'+myName.substring(5);` – user924 Nov 04 '18 at 14:31
  • 2
    Keep in mind this copies the String twice. It's probably faster to use the String concatenation version instead. – Ariel Nov 11 '20 at 01:46
22

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.

Ardent Coder
  • 3,777
  • 9
  • 27
  • 53
no name
  • 522
  • 4
  • 13
18

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

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();
    }
}
C.Champagne
  • 5,381
  • 2
  • 23
  • 35
10

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.

fenceop
  • 1,439
  • 3
  • 18
  • 29
CodeMed
  • 9,527
  • 70
  • 212
  • 364
  • 1
    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. – C.Champagne Oct 20 '15 at 12:47
1

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.

kazinix
  • 28,987
  • 33
  • 107
  • 157
0

You can overwrite on same string like this

String myName = "domanokz";
myName = myName.substring(0, index) + replacement + myName.substring(index+1); 

where index = the index of char to replacement. index+1 to add rest of your string

Hamodea Net
  • 105
  • 1
  • 1
  • 10
-9

this will work

   String myName="domanokz";
   String p=myName.replace(myName.charAt(4),'x');
   System.out.println(p);

Output : domaxokz

Rachel Gallen
  • 27,943
  • 21
  • 72
  • 81