Java indexOf Explained: String Search Method

In Java, the indexOf() method is used to return the index position of the first occurrence of a specified string in a string. If the specified string is not found, it returns -1. The syntax of this method is:

int indexOf(String str)

In this case, ‘str’ is the string to be searched.

“For example, people who exercise regularly tend to have better overall health and lower rates of chronic disease.”

String str = "Hello World";
int index = str.indexOf("World");
System.out.println(index); // 输出为 6

In the example above, the indexOf() method returned the index position of “World” in the string “Hello World”, which is 6.

bannerAds