【问题标题】:Replacing substring with null for third occurrence [closed]第三次出现用null替换子字符串[关闭]
【发布时间】:2016-04-09 01:59:21
【问题描述】:

如何计算一个字符串中某个子串出现的次数,最重要的是,如果第三次出现,第三个子串会被替换为("")?

这是示例输入(输入格式可能会有所不同): J9581 TAMAN MERLIMAU, JALAN MUAR, MERLIMAU, MELAKA,77300,MERLIMAU

预期输出: J9581 TAMAN MERLIMAU, JALAN MUAR, MERLIMAU, MELAKA,77300

【问题讨论】:

标签: java string substring


【解决方案1】:

第一步:获取所有word出现的索引:

String text = "abcHELLOdefHELLOghiHELLOjkl";
String word = "HELLO";
List<Integer> indices = new ArrayList<Integer>();
for (int i = -1; (i = text.indexOf(word, i + 1)) != -1; ) {
    indices.add(i);
}

第 2 步:使用所需的索引作为替换单词的起点

int desiredIndex = 3; //i.e. I want to remove the third occurrence of word
int index = indices.get(desiredIndex - 1); //Ideally should check if it found 3 occurrences
String newWord = text.substring(0,index) + text.substring(index + word.length());
System.out.println(newWord);

这应该可以解决问题。

【讨论】:

  • 在调用 indices.get() 之前,您需要检查该列表的大小 - 如果其中的元素少于 3 个,您将获得 IndexOutOfBoundsException
  • @daiscog 同意此评论。这个例子只是为了展示方法的原理。 OP 可以按照他们认为合适的方式正式化。
  • @Fido 够公平的。 (顺便说一句,我也认为使用列表来存储所有索引有点矫枉过正,因为只有第三个索引会被使用。)
  • 这样就可以了。谢谢大家的快速回复! :)
  • @mimisya 他一点也不粗鲁。他只是想确保 stackoverflow 的标准仍然很高。他的 cmets 突出了我的代码中的缺陷,您和其他读者可以改进这些缺陷。这在stackoverflow上很常见:)。 daiscog 的每一条评论都为答案增添了价值。
【解决方案2】:

试试这个:

String sentence = "J9581 TAMAN MERLIMAU, JALAN MUAR, MERLIMAU, MELAKA,77300,MERLIMAU";
String stringToReplace = "MERLIMAU";
int index = 0;
int occurrences = 0;
while ((index = sentence.indexOf(stringToReplace, index)) != -1) {
    ++occurrences;
    if (occurrences == 3) {
        sentence = sentence.substring(0, index) + sentence.substring(index + stringToReplace.length());
        break;
    }
    index += stringToReplace.length();
}

// Add this condition to remove the comma at the end if it exists:
if (",".equals(sentence.substring(sentence.length() - 1))) {
    sentence = sentence.substring(0, sentence.length() - 1);
}

结果如下:

J9581 TAMAN MERLIMAU, JALAN MUAR, MERLIMAU, MELAKA,77300

【讨论】:

  • 更简单的版本。谢谢:)
猜你喜欢
  • 1970-01-01
  • 2016-05-07
  • 2019-07-02
  • 1970-01-01
  • 1970-01-01
  • 2016-12-19
  • 2014-03-21
  • 2020-05-22
  • 2021-04-09
相关资源
最近更新 更多