【问题标题】:Replace multiple occurences of substring with conditional substring that includes the original substring用包含原始子字符串的条件子字符串替换多次出现的子字符串
【发布时间】: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


    【解决方案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.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-07
      • 2020-04-05
      • 2017-04-16
      • 2014-06-12
      • 1970-01-01
      • 1970-01-01
      • 2017-03-23
      • 1970-01-01
      相关资源
      最近更新 更多