我有一个关于替换某些字符的问题。 我有一个由 x 个字符组成的字符串,其中包含正常英语字母表中的所有字符。
String x = "exampleString"
我的问题是,因为我想要做的是替换该字符串中的字符,所以我无法进行用户替换,因为这会替换之前替换的字符串,例如。
if(x.contains(e)){
x = x.replace("e","a")
}
这将替换上面字符串中的每个 E 字符。
我也尝试使用:
x=x.replace("e","a").replace("a","b")
但这也会替换每个字符,甚至是之前替换的字符。 我认为这可行,因为字符串在 Java 中是不可变的,但事实并非如此。
我还考虑使用计数器来查看字符串何时被替换并省略替换的字符串,但是我无法实现这一点。
有人可以建议解决方案吗?
问候 编程新手。
最佳答案
你可以试试这个:
// Your String
String str = "exampleString";
// Convert it to a Character array.
char[] strCharArr = str.toCharArray();
// Have a corresponding boolean array
boolean[] arrStr = new boolean[str.length()];
// Character to be replaced
char a = 'r';
// Character to be replaced with
char b = 's';
// Loop through the array
for(int i = 0; i < strCharArr.length; i++) {
// Check if the characted matches and have not been replaced before.
if(strCharArr[i] == a && !arrStr[i]) {
strCharArr[i] = b;
arrStr[i] = true;
}
}
System.out.println(String.valueOf(strCharArr));
// Now if you need to replace again.
a = 's';
b = 'a';
for(int i = 0; i < strCharArr.length; i++) {
if(strCharArr[i] == a && !arrStr[i]) {
strCharArr[i] = b;
arrStr[i] = true;
}
}
System.out.println(String.valueOf(strCharArr));
之后您可以将字符数组转换回相应的字符串。您可以编写一个函数并根据需要多次替换它。
关于java - 仅替换未替换的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53403417/