【发布时间】:2017-04-09 18:14:16
【问题描述】:
对不起,标题很长,但作为初学者,我在这里不知所措......可能我找不到现有的解决方案,因为我不知道要搜索的术语。
我想要做的是用一些包含原始子字符串的条件子字符串替换字符串中的所有子字符串。一个例子可能更清楚:
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"
所以子字符串“me”应该被它自己加上一些有条件的东西替换。到目前为止我尝试的方法不起作用,因为我一直在替换替换的子字符串。所以我最终得到:
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);
}
}
我不知道如何不替换已替换的字符串的子字符串部分。
【问题讨论】:
标签: java string replace substring