Java String indexOf
Well, with this method, we are getting the first occurrence (index) of the string that we are providing as an argument. This is like saying – hey… take this string, and tell me where this string has first occurred in the specified string. Just give me the index of the first occurrence of this particular string.
If you feel confused, just let’s consider an example to get a clearer picture of this method –
if we have a String str1 = ”This food house serves good food”;
so, if we are using the indexOf method here, and give the string ”food” as an argument to this method, we get an output as 5, which is the starting index of ”food”. Now if you are wondering that there were 2 food there, then why did it pick up the first one? Well, this is what it does. It is searching for the first occurrence of the given string.
public class StringMethods {
public static void main(String[] args) {
String str1 = “This food house serves good food”;
System.out.println(str1.indexOf(“food”));
}
}
If we try to execute the program, we get an output as 5, which is the index where the word food starts. You can manually check this out by starting counting from 0 to 5, and at 5, starts food.
But let’s consider one more case, that the string you are searching for does not exist there. Like if in the above string, I search for ”burger”, which is never there. What would happen in this case? Let’s see –
public class StringMethods {
public static void main(String[] args) {
String str1 = “This food house serves good food”;
System.out.println(str1.indexOf(“burger”));
}
}
If we try executing this program, we find the output to be -1. so, a -1 just says that the string you are searching for isn’t present.
One more thing, that we can also find the index of some character instead of a string. So, lets now see how can we do that –
public class StringMethods {
public static void main(String[] args) {
String str1 = “This food house serves good food”;
System.out.println(str1.indexOf(‘h’));
}
}
So, in the above program, we are just finding the first occurrence of the character ‘h’. Just by seeing the string, we can tell that hey… the character ‘h’ first occurred at index 1.
Again here also, if we try to search for such a character that is not at all present in the string, then this also returns -1.