Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Replace Character At Specific Position Of String? [duplicate]

I am trying to replace a character at a specific position of a string.

For example:

String str = "hi"; 

replace string position #2 (i) to another letter "k"

How would I do this? Thanks!

like image 503
01jayss Avatar asked Jul 21 '12 02:07

01jayss


People also ask

How do you replace a character in a specific position in a string Java?

String are immutable in Java. You can't change them. You need to create a new string with the character replaced.

What is the difference between Replace () and replaceAll ()?

The difference between replace() and replaceAll() method is that the replace() method replaces all the occurrences of old char with new char while replaceAll() method replaces all the occurrences of old string with the new string.


2 Answers

Petar Ivanov's answer to replace a character at a specific index in a string question

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 62
waldyr.ar Avatar answered Sep 23 '22 19:09

waldyr.ar


Kay!

First of all, when dealing with strings you have to refer to their positions in 0 base convention. This means that if you have a string like this:

String str = "hi"; //str length is equal 2 but the character //'h' is in the position 0 and character 'i' is in the postion 1 


With that in mind, the best way to tackle this problem is creating a method to replace a character at a given position in a string like this:

Method:

public String changeCharInPosition(int position, char ch, String str){     char[] charArray = str.toCharArray();     charArray[position] = ch;     return new String(charArray); } 

Then you should call the method 'changeCharInPosition' in this way:

String str = "hi"; str = changeCharInPosition(1, 'k', str); System.out.print(str); //this will return "hk" 

If you have any questions, don't hesitate, post something!

like image 32
Chicodelarose Avatar answered Sep 25 '22 19:09

Chicodelarose