43

我正在尝试替换字符串特定位置的字符。

例如:

String str = "hi";

将字符串位置 #2 (i) 替换为另一个字母“k”

我该怎么做?谢谢!

4

5 回答 5

52

Petar Ivanov的答案以替换字符串问题中特定索引处的字符

字符串在 Java 中是不可变的。你不能改变它们。

您需要创建一个替换字符的新字符串。

String myName = "domanokz";
String newName = myName.substring(0,4)+'x'+myName.substring(5);

或者您可以使用 StringBuilder:

StringBuilder myName = new StringBuilder("domanokz");
myName.setCharAt(4, 'x');

System.out.println(myName);
于 2012-07-21T02:10:26.783 回答
17

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!

于 2012-07-21T07:47:54.420 回答
15

使用StringBuilder

StringBuilder sb = new StringBuilder(str);
sb.setCharAt(i - 1, 'k');
str = sb.toString();
于 2013-05-01T13:11:11.793 回答
14

替换指定位置的字符:

public static String replaceCharAt(String s, int pos, char c) {
   return s.substring(0,pos) + c + s.substring(pos+1);
}
于 2013-05-01T13:04:11.433 回答
4

如果您需要重用字符串,请使用StringBuffer

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

编辑:

请注意,StringBuffer是线程安全的,而使用StringBuilder更快,但不是线程安全的。

于 2015-06-16T15:01:36.013 回答