Tuesday 2 November 2021

Java: Get the index of first occurrence of a substring

Approach 1: Using indexOf method.

String class provides ‘indexOf’ method, which takes a string as argument and returns the index within this string of the first occurrence of the specified substring. If this string does not contain any occurrence, then it returns -1.

 

Example

String str = "abrakadabra";
int brIndex = str.indexOf("br");

 

IndexOfDemo.java

package com.sample.app.strings;

public class IndexOfDemo {

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

		int brIndex = str.indexOf("br");
		int xyIndex = str.indexOf("xy");

		System.out.println("str -> " + str);
		System.out.println("brIndex -> " + brIndex);
		System.out.println("xyIndex -> " + xyIndex);
	}

}

 

Output

str -> abrakadabra
brIndex -> 1
xyIndex -> -1

 

Approach 2: Using regular expression.

 

IndexOfUsingRegexDemo.java

package com.sample.app.strings;

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

public class IndexOfUsingRegexDemo {

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

		Pattern word = Pattern.compile("br");
		Matcher match = word.matcher(str);

		while (match.find()) {
			System.out.println("Found \"br\" at index " + match.start());
			break;
		}

	}

}

 

Output

Found "br" at index 1

 

Reference

https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#indexOf(java.lang.String)

 

 

 

You may like

Interview Questions

How HashSet behave while adding a duplicate value?

How to call a method asynchronously in Java?

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?

No comments:

Post a Comment