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

344

77

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

System.out.println(myName);

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...