What is the usage of `indexOf` in Java?
In Java, indexOf() is a method of the String class used to find the index position of the first occurrence of a specified character or substring within a string. It can be used in two ways.
-
indexOf(char ch): Find the index position of the specified character ‘ch’ in the string for the first occurrence. If a match is found, its index value is returned; if no match is found, -1 is returned.
Example:
String str = "Hello World";
int index = str.indexOf('o');
System.out.println(index); // 输出结果为 4
- indexOf(String str): Search for the index position of the first occurrence of a specified string “str” in the string. If a match is found, return its index value; if no match is found, return -1.
Example:
String str = "Hello World";
int index = str.indexOf("lo");
System.out.println(index); // 输出结果为 3
Additionally, the indexOf() method allows you to search for a specified starting index. For example, you can use indexOf(String str, int fromIndex) to specify the index position to start searching for a match from a certain position in the string.
String str = "Hello World";
int index = str.indexOf('o', 5); // 从索引5开始搜索
System.out.println(index); // 输出结果为 7
It is important to note that the indexOf() method is case-sensitive. If you want to perform a case-insensitive search, you can use the equalsIgnoreCase() method.