第三次出现时将子字符串替换为null

时间:2016-01-05 09:39:17

标签: java string substring

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

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

预期产量: J9581 TAMAN MERLIMAU,JALAN MUAR,MERLIMAU,MELAKA,77300

2 个答案:

答案 0 :(得分:4)

第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);

这应该可以解决问题。

答案 1 :(得分: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