在字符串中随机替换某个单词有限次数| Java的

时间:2013-04-27 01:33:19

标签: java string replace

我想从字符串中替换一个单词,就像string.replace("word", "different word");的工作方式一样,只是有限次数,让我们在字符串中提到单词apple 10次,我希望apples中的5个成为oranges,我怎么能实现这一目标?

另外,如果可能的话,我希望它是随机的,所以它不会从第一个apple开始,而是跳过,例如更改1st, 3rd, 4th, 7th, and 8th apple会发生变化。

谢谢!

2 个答案:

答案 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)