我尝试过代码来替换特定字符。在字符串中有三个相同的字符,我只想替换第二个或第三个字符。例如:
Cannot Deposit - Account Is Frozen
在这个字符串中有三个'i'字符。我想只替换第二个或第三个字符。所以,字符串将是
String line = "this.a[i] = i";
这是我读取字符串并用另一个字符串替换它的代码:
String line = "this.a[i] = "newChar";
获取角色的方法:
String EQ_VAR;
EQ_VAR = getequals(line);
int length = EQ_VAR.length();
if(length == 1){
int gindex = EQ_VAR.indexOf(EQ_VAR);
StringBuilder nsb = new StringBuilder(line);
nsb.replace(gindex, gindex, "New String");
}
我只是假设使用索引是替换特定字符的最佳选择。我尝试使用字符串String getequals(String str){
int startIdx = str.indexOf("=");
int endIdx = str.indexOf(";");
String content = str.substring(startIdx + 1, endIdx);
return content;
}
,但随后所有'i'字符都被替换,结果字符串如下所示:
replace
答案 0 :(得分:0)
除了前几个,你可以用一种方法来替换所有的出现:
String str = "This is a text containing many i many iiii = i";
String replacement = "hua";
String toReplace = str.substring(str.indexOf("=")+1, str.length()).trim(); // Yup, gets stuff after "=".
int charsToNotReplace = 1; // Will ignore these number of chars counting from start of string
// First replace all the parts
str = str.replaceAll(toReplace, replacement);
// Then replace "charsToNotReplace" number of occurrences back with original chars.
for(int i = 0; i < charsToNotReplace; i++)
str = str.replaceFirst(replacement, toReplace);
// Just trim from "="
str = str.substring(0, str.indexOf("=")-1);
System.out.println(str);
结果:This huas a text contahuanhuang many hua many huahuahuahua;
您将set charsToNotReplace
设置为要忽略的第一个字符数。例如,将其设置为2将忽略替换前两次出现(从技术角度来说)。