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!
String are immutable in Java. You can't change them. You need to create a new string with the character replaced.
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.
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);
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With