Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a character at a specific index in a string?

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?

like image 511
dpp Avatar asked Aug 05 '11 06:08

dpp


People also ask

How do you replace a specific character in a string?

Using 'str.replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.

How do you replace a character in a string at a specific index Python?

replace() method helps to replace the occurrence of the given old character with the new character or substring. The method contains the parameters like old(a character that you wish to replace), new(a new character you would like to replace with), and count(a number of times you want to replace the character).


1 Answers

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); 
like image 188
Petar Ivanov Avatar answered Oct 12 '22 03:10

Petar Ivanov