46

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!

Kijewski
  • 25,517
  • 12
  • 101
  • 143
01jayss
  • 1,400
  • 6
  • 19
  • 28

5 Answers5

54

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);
Community
  • 1
  • 1
waldyr.ar
  • 14,424
  • 6
  • 33
  • 64
18

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!

Chicodelarose
  • 827
  • 7
  • 22
15

Use StringBuilder:

StringBuilder sb = new StringBuilder(str);
sb.setCharAt(i - 1, 'k');
str = sb.toString();
Bohemian
  • 412,405
  • 93
  • 575
  • 722
14

To replace a character at a specified position :

public static String replaceCharAt(String s, int pos, char c) {
   return s.substring(0,pos) + c + s.substring(pos+1);
}
Ajay
  • 4,850
  • 2
  • 32
  • 44
4

If you need to re-use a string, then use StringBuffer:

String str = "hi";
StringBuffer sb = new StringBuffer(str);
while (...) {
    sb.setCharAt(1, 'k');
}

EDIT:

Note that StringBuffer is thread-safe, while using StringBuilder is faster, but not thread-safe.

Borzh
  • 5,069
  • 2
  • 48
  • 64