我正在尝试创建一种方法,用新字符替换单词中特定字符的所有实例。这是我目前所拥有的:
public class practice {
public static void main(String[] args) {
String test3 = updatePartialword("----", "test", 't');
System.out.println(test3); }
public static String updatePartialword(String partial, String secret, char c) {
String newPartial = "";
int len = secret.length();
for (int i=0; i<=secret.length()-1; i++){
char x = secret.charAt(i);
if (c==x) {
String first = partial.substring(0,i);
String second = partial.substring(i+1,len);
newPartial = first+x+second;
}
}
return newPartial;
}
}
我希望它返回 t--t,但它只会打印最后一个 t。任何帮助将不胜感激!
最佳答案
Java 已经在 String 中为此内置了一个方法。您可以使用 replace()
用另一个字符替换字符串中所有出现的给定字符的方法
String str = "Hello";
str.replace('l', '-'); //Returns He--o
str.replace('H', '-'); //Returns -ello
关于java - 替换字符串中某个字符的所有实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33714931/