Tuesday, 2 November 2021

Java: Get all the indexes of occurrence of a substring

Approach 1: Using indexOf method

 

public int indexOf(String str, int fromIndex)

Return the index of the first occurrence of the specified substring, starting at the specified index, or -1 if there is no such occurrence.

        

AllTheOccurrencesOfSubstring.java

package com.sample.app.strings;

public class AllTheOccurrencesOfSubstring {
	
	private static void printAllOccurrences(String str, String subStr) {
		int startIndex = -1;
		
		while((startIndex = str.indexOf(subStr, startIndex+1)) != -1) {
			System.out.println("index -> " + startIndex);
		}
	}

	public static void main(String args[]) {
		String str = "abrakadabra";

		printAllOccurrences(str, "ab");
	}

}

 

Output

index -> 0
index -> 7

 

Approach 2: Using regular expressions.

 

AllTheOccurrencesOfSubstring1.java

 

package com.sample.app.strings;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AllTheOccurrencesOfSubstring1 {

	private static void printAllOccurrences(String str, String subStr) {
		Pattern word = Pattern.compile(subStr);
		Matcher match = word.matcher(str);

		while (match.find()) {
			System.out.println("index -> " + match.start());
		}
	}

	public static void main(String args[]) {
		String str = "abrakadabra";

		printAllOccurrences(str, "ab");
	}

}

Output

index -> 0
index -> 7


You may like

Interview Questions

How method overloading works with null values in Java?

Java: How to find maximum element in a collection?

Java: How to find the minimum element in a collection?

Java: Get the index of first occurrence of a substring

Java: Get the index of last occurrence of a substring

No comments:

Post a Comment