我想从字符串中替换一个单词,就像string.replace("word", "different word");
工作方式一样,只是次数有限,假设该单词apple
在字符串中被提及 10 次,我希望apples
成为5 个,我oranges
怎么能做到这一点?
另外,如果可能的话,我希望它是随机的,所以它不会从第一个到第五个apple
而是跳过,例如改变1st, 3rd, 4th, 7th, and 8th apple
会改变。
谢谢!
我会做随机子字符串并replaceFirst
在它们上使用方法。对于子串,使用substring(int beginIndex)和介于 0 和 lengthOfOriginalWord-1-lengthOfWordToReplace 间隔之间的随机开始索引。
try {
String originalWord = "alabalaportocalaORANGEalabalaportocalaORANGEalabalaportocalaORANGEalabalaportocalaORANGEalabalaORANGEORANGEaaaaaaa";
String replacedWord = "ORANGE";
String replacingWord = "APPLE";
String substringedWord = "";
// make sure this is smaller or equal with the number of occurrences, otherwise it's endless loop times
int numberOfReplaces = 3;
Random ran = new Random();
int beginIndex;
while (numberOfReplaces > 0) {
// random index between 0 and originalWord.length()-1-replacedWord.length()
beginIndex = ran.nextInt(originalWord.length()-1-replacedWord.length());
substringedWord = originalWord.substring(beginIndex);
if (substringedWord.contains(replacedWord)) {
originalWord = originalWord.substring(0, beginIndex) + substringedWord.replaceFirst(replacedWord, replacingWord);
numberOfReplaces--;
}
}
System.out.println(originalWord);
} catch (Exception exc) {
System.err.println("An error occurred: \n" + exc);
}
这是运行五次后的输出:
alabalaportocalaORANGEalabalaportocalaORANGEalabalaportocalaORANGEalabalaportocalaAPPLEalabalaAPPLEAPPLEaaaaaaa
alabalaportocalaAPPLEalabalaportocalaAPPLEalabalaportocalaAPPLEalabalaportocalaORANGEalabalaORANGEORANGEaaaaaaa
alabalaportocalaAPPLEalabalaportocalaORANGEalabalaportocalaORANGEalabalaportocalaAPPLEalabalaAPPLEORANGEaaaaaaa
alabalaportocalaORANGEalabalaportocalaORANGEalabalaportocalaORANGEalabalaportocalaAPPLEalabalaAPPLEAPPLEaaaaaaa
alabalaportocalaAPPLEalabalaportocalaORANGEalabalaportocalaAPPLEalabalaportocalaAPPLEalabalaORANGEORANGEaaaaaaa
您可以迭代地使用String#indexOf(String str, int fromIndex)
来查找要替换的单词的所有起始索引,然后随机选择其中一些索引(使用例如 shuffledArrayList<Integer>
或替代ArrayList<Integer>#remove(Random#nextInt(ArrayList#size))
)并使用连接调用构造新字符串String#substring(int beginIndex, int endIndex)
ArrayList<Integer> indices = new ArrayList<>();
int fromIndex = str.indexOf(searchString);
while(fromIndex != -1) {
indices.add(fromIndex);
fromIndex = str.indexOf(searchString, fromIndex + 1);
}