Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing substring with null for third occurrence [closed]

How can I calculate the number of occurrences of a substring in a string and most importantly, if it occurs for the third time, the third substring will be replaced with ("")?

this is the sample input (the input format may be vary): J9581 TAMAN MERLIMAU, JALAN MUAR, MERLIMAU, MELAKA,77300,MERLIMAU

expected output: J9581 TAMAN MERLIMAU, JALAN MUAR, MERLIMAU, MELAKA,77300

like image 731
ohlala Avatar asked Nov 30 '25 03:11

ohlala


1 Answers

Step 1: Get the indices of all occurrences of 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);
}

Step 2: Use the desired index as the start point for replacing the word

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

That should do the trick.

like image 197
Filipe Teixeira Avatar answered Dec 01 '25 18:12

Filipe Teixeira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!