Which method returns the index within calling String object of first occurrence of specified value ?
In this article, we will know how to return the index of the first occurrence of the specified value(can be a string or character) in the string, also will understand their implementation through the examples.
The main usage of this method is to find the existence of the particular string or character in the string because the method returns -1 if the provided search value is not present. This method can also be used to calculate the frequency of specific search value in the string.
Example 1: This example illustrates the search value that can be a string or any character.
The index of 'Hello' in string is: 0 The index of first occurrence of 'G' is: 7
Explanation: In the first line, we have declared a string with initialization, and later we are calling the indexOf() method with this string as a calling object by providing the “Hello” as an argument. Now, this method will return the first occurrence of “Hello” in the string which is 0. After then, we have searched for the character ‘G’ in the string. Here, this method will return 7 because that is the first occurrence.
Example 2: This example describes finding the first occurrence of the argument character or string wrt to the specific position.
The index of first occurrence 'i' from 3rd index is: 10 The index of first occurrence 'Hi' from the 7th index is: -1
Explanation: Here, we are calling the indexOf() method by providing the start index of searching explicitly, In the first one, we are calling the method by providing ‘i’ and 3. The ‘i’ will be found on the 10th index if the starting search index is 3. Similarly in the second one, we have provided the ‘Hi’ for searching from the 7th index but there is no occurrence of “Hi” after the 7th index hence -1 will be returned.
Please Login to comment...