0 votes
1 view
in Java by (3.4k points)



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?

1 Answer

0 votes
by (46.1k points)

You can't change the String in Java as they are immutable. 

You require to generate a distinct string with the character restored.

String myName = "domanokz";

String newName = myName.substring(0,4)+'x'+myName.substring(5);

Or you can try a StringBuilder:

StringBuilder myName = new StringBuilder("domanokz");

myName.setCharAt(4, 'x');


Related questions

0 votes
1 answer
+1 vote
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !