Get the index of the 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.
Example – Get the index of first occurrence of a substring
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 { public static void main(String[] args) { //initialize strings String str1 = "hello world good morning. good day."; String str2 = "good"; //get the index of str2 in str1 int indexOfSubStr = str1.indexOf(str2); System.out.println("str2 first appeared in str1 at index : "+ indexOfSubStr); } }When the above program is run, the output to the console is as shown below :
str2 first appeared in str1 at index : 12Example – Get the index of first occurrence of a substring – Ignore Case
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 { public static void main(String[] args) { //initialize strings String str1 = "hello world GoOd morning. gOOD day."; String str2 = "GOOD"; //ignore case and get the index of str2 in str1 int indexOfSubStr = str1.toLowerCase().indexOf(str2.toLowerCase()); System.out.println("str2 first appeared in str1 at index : "+ indexOfSubStr); } }Run the program.
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.
The indexOf() method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the first occurrence of the specified substring. Given a second argument: a number, the method returns the first occurrence of the specified substring at an index greater than or equal to the specified number. indexOf(searchString)
indexOf(searchString, position)
searchString Substring to search for, coerced to a string. If the method is called with no arguments, searchString is coerced to "undefined".
Therefore,"undefined".indexOf() returns 0 — because the substring "undefined" is found at position 0 in the string "undefined". But "undefine".indexOf(), returns -1 — because the substring "undefined" is not found in the string "undefine". The method returns the index of the first occurrence of the specified substring at a position greater than or equal to position, which defaults to 0. If position is greater than the length of the
calling string, the method doesn't search the calling string at all. If position is less than zero, the method behaves as it would if position were 0.Try it
Syntax
Parameters
Return value
The index of the first occurrence of searchString found, or -1 if not found.
Return value when using an empty search string
Searching for an empty search string produces strange results. With no second argument, or with a second argument whose value is less than the calling string's length, the return value is the same as the value of the second argument:
'hello world'.indexOf('') // returns 0 'hello world'.indexOf('', 0) // returns 0 'hello world'.indexOf('', 3) // returns 3 'hello world'.indexOf('', 8) // returns 8
However, with a second argument whose value is greater than or equal to the string's length, the return value is the string's length:
'hello world'.indexOf('', 11) // returns 11 'hello world'.indexOf('', 13) // returns 11 'hello world'.indexOf('', 22) // returns 11
In the former instance, the method behaves as if it found an empty string just after the position specified in the second argument. In the latter instance, the method behaves as if it found an empty string at the end of the calling string.
Description
Strings are zero-indexed: The index of a string's first character is 0, and the index of a string's last character is the length of the string minus 1.
'Blue Whale'.indexOf('Blue') // returns 0 'Blue Whale'.indexOf('Blute') // returns -1 'Blue Whale'.indexOf('Whale', 0) // returns 5 'Blue Whale'.indexOf('Whale', 5) // returns 5 'Blue Whale'.indexOf('Whale', 7) // returns -1 'Blue Whale'.indexOf('') // returns 0 'Blue Whale'.indexOf('', 9) // returns 9 'Blue Whale'.indexOf('', 10) // returns 10 'Blue Whale'.indexOf('', 11) // returns 10
The indexOf() method is case sensitive. For example, the following expression returns -1:
'Blue Whale'.indexOf('blue') // returns -1
Checking occurrences
When checking if a specific substring occurs within a string, the correct way to check is test whether the return value is -1:
'Blue Whale'.indexOf('Blue') !== -1 // true; found 'Blue' in 'Blue Whale' 'Blue Whale'.indexOf('Bloe') !== -1 // false; no 'Bloe' in 'Blue Whale'
Examples
Using indexOf()
The following example uses indexOf() to locate substrings in the string "Brave new world".
const str = 'Brave new world'; console.log(str.indexOf('w')); // 8 console.log(str.indexOf('new')); // 6
indexOf() and case-sensitivity
The following example defines two string variables.
The variables contain the same string, except that the second string contains uppercase letters. The first console.log() method displays 19. But because the indexOf() method is case sensitive, the string "cheddar" is not found in myCapString, so the second console.log() method displays -1.
const myString = 'brie, pepper jack, cheddar'; const myCapString = 'Brie, Pepper Jack, Cheddar'; console.log(myString.indexOf('cheddar')); // 19 console.log(myCapString.indexOf('cheddar')); // -1
Using indexOf() to count occurrences of a letter in a string
The following example sets count to the number of occurrences of the letter e in the string str:
const str = 'To be, or not to be, that is the question.'; let count = 0; let position = str.indexOf('e'); while (position !== -1) { count++; position = str.indexOf('e', position + 1); } console.log(count); // 4
Specifications
ECMAScript Language Specification # sec-string.prototype.indexof |
Browser compatibility
BCD tables only load in the browser