indexOf
public int indexOf(String str) returns the index of the first occurrence of the specified substring in this string. The returned integer is the smallest value of k for which
this.startsWith(str, k)
is true.
Parameters:
str - an arbitrary string.
Returns:
If the string argument appears as a substring in this object, returns the index of the first character of the first such substring; if it does not appear as a substring, returns -1.
According to the description, this method can be used to determine whether a string is in another string.
The index starts from 0. If the string does not contain another string, it returns -1. The
following demo is easy to understand.
package test; public class Test { public static void main(String[] args) { String x = "Hello World/XXX"; String y = "Hello World/"; System.out.println("Returns the index value of the first occurrence of y in x: "+x.indexOf(y)); System.out.println("Returns the index value of the first occurrence of x in y: "+y.indexOf(x)); if(x.indexOf(y)!=-1){ System.out.println("x包含y"); }else{ System.out.println("x does not contain y"); } } }
Result:
Returns the index value of the first occurrence of y in x: 0
Returns the index value of the first occurrence of x in y: -1
x contains y