我想从字符串中替换一个单词,就像string.replace("word", "different word");
的工作方式一样,只是有限次数,让我们在字符串中提到单词apple
10次,我希望apples
中的5个成为oranges
,我怎么能实现这一目标?
另外,如果可能的话,我希望它是随机的,所以它不会从第一个apple
开始,而是跳过,例如更改1st, 3rd, 4th, 7th, and 8th apple
会发生变化。
谢谢!
答案 0 :(得分:2)
我会做随机子串并在那些上使用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
答案 1 :(得分:1)
您可以迭代地使用String#indexOf(String str, int fromIndex)
来查找要替换的单词的所有起始索引,然后随机选择其中一些索引(例如使用混洗ArrayList<Integer>
,或者{{{ 1}})并使用ArrayList<Integer>#remove(Random#nextInt(ArrayList#size))
String#substring(int beginIndex, int endIndex)