我正在尝试替换字符串特定位置的字符。
例如:
String str = "hi";
将字符串位置 #2 (i) 替换为另一个字母“k”
我该怎么做?谢谢!
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);
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!
使用StringBuilder
:
StringBuilder sb = new StringBuilder(str);
sb.setCharAt(i - 1, 'k');
str = sb.toString();
替换指定位置的字符:
public static String replaceCharAt(String s, int pos, char c) {
return s.substring(0,pos) + c + s.substring(pos+1);
}
如果您需要重用字符串,请使用StringBuffer:
String str = "hi";
StringBuffer sb = new StringBuffer(str);
while (...) {
sb.setCharAt(1, 'k');
}
编辑:
请注意,StringBuffer是线程安全的,而使用StringBuilder更快,但不是线程安全的。