很抱歉这个标题很长,但我作为一个初学者不知所措......可能我找不到现有的解决方案,因为我不知道要搜索的条款。
我尝试做的是用一些包含原始子字符串的条件子字符串替换字符串中的所有子字符串。一个例子可能更清楚:
String answerIN = "Hello, it is me. It is me myself and I."
//should become something like:
String answerOUT = "Hello, it is <sync:0> me. It is <sync:1> me myself and I"
所以子串&#34; me&#34;应该由自己加上一些有条件的东西来代替。到目前为止我尝试的东西不起作用,因为我一直在替换被替换的子串。所以我最终得到了:
String answerOUT = "Hello, it is <sync:0> <sync:1> me. It is <sync:0> <sync:1> me myself and I"
我的代码:
String answerIN = "Hello, it is me. It is me myself and I.";
String keyword = "me";
int nrKeywords = 2; //I count this in the program but that's not the issue here
if (nrKeywords != 0){
for (int i = 0; i < nrKeywords; i++){
action = " <sync" + i + "> " + keyword;
answerIN = answerIN.replace(keyword, action);
System.out.println("New answer: " + answerIN);
}
}
我无法弄清楚如何不替换已经替换过的字符串的子串部分。
答案 0 :(得分:1)
String#replace
将始终用您想要替换它的内容替换您正在寻找的String
的每个出现。因此,常规String#replace
无法做到这一点,因为没有“只能从这里替换到那里”。
您可以使用String
的子字符串方法来替换每个出现的事项:
String input = "Hello, it is me. It is me myself and I.";
String output = "";
String keyword = "me";
int nextIndex = input.indexOf(keyword), oldIndex = 0, counter = 0;
while(nextIndex != -1) {
output += input.substring(oldIndex, nextIndex-1) + " <sync:" + counter + "> ";
oldIndex = nextIndex;
nextIndex = input.indexOf(keyword, nextIndex+1);
++counter;
}
output += input.substring(oldIndex);
System.out.println(output);
O / P
Hello, it is <sync:0> me. It is <sync:1> me myself and I.