Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
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 (46k 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

0 votes
1 answer
0 votes
1 answer
+1 vote
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...