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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With