Get The Index of First Occurrence of A Substring in A String Using Java
Get The Index of First Occurrence of A Substring in A String Using Java
To find the index of first occurrence of a substring in a string you can use String.indexOf() function.
A string, say str2 , can occur in another string, say str1 , n number of times. There could be a
requirement in your Java application, that you have to find the position of the first occurrence of str2 in
str1 . Or you may need to find nth occurrence.
In this tutorial, we shall learn to get the index of first occurrence of a string in another string using Java.
We shall make use of String.indexOf(String otherString) method, to find the index of first
occurrence of string str2 in str1 . If the string str2 is present in the other string str1 , it returns the
index of its first occurrence. If it is not present, then it returns -1 indicating that the string str2 is not
present in the string str1 .
In this example, we shall initialize two strings with variable names str1 and str2 . And we are going to find
the first occurrence of str2 in str1 .
/**
* Java Example program to find the index of first occurrence of a substring in a string
*/
public class FirstOccurrenceExample {
In this example, we ignore the case of both the strings and try to find the occurrence of string str2 in string
str1 . To ignore the case, we have actually converted the strings to lowercase and then applied the function
indexOf().
Please note that with the strings str1 and str2 in the below program, if you consider the case, indexOf() would
return -1 . But as we are ignoring the case, we got str2="GOOD" and GoOd in str1 matched.
/**
* Java Example program to find the index of first occurrence of a substring in a string
*/
public class FirstOccurrenceExample {
Conclusion
In this Java Tutorial, we have learned how to get index of first occurrence of a substring in a String, by
considering or ignoring the case of alphabets.
✦ Java Tutorial
✦ Java String