indexOf
public int indexOf(String str)返回指定子字符串在此字符串中第一次出现处的索引。返回的整数是
this.startsWith(str, k)
为 true 的最小 k 值。
参数:
str - 任意字符串。
返回:
如果字符串参数作为一个子字符串在此对象中出现,则返回第一个这种子字符串的第一个字符的索引;如果它不作为一个子字符串出现,则返回 -1。
依据描述可利用该方法实现判断一个字符串是否在另外一个字符串中。
索引都是从0开始的,如果出现字符串不包含另一个字符串,则返回-1.
如下demo方便理解。
package test; public class Test { public static void main(String[] args) { String x = "Hello World/XXX"; String y = "Hello World/"; System.out.println("返回 y 在x 中第一次出现处的索引值为:"+x.indexOf(y)); System.out.println("返回 x 在y 中第一次出现处的索引值为:"+y.indexOf(x)); if(x.indexOf(y)!=-1){ System.out.println("x包含y"); }else{ System.out.println("x不包含y"); } } }
运行结果:
返回 y 在x 中第一次出现处的索引值为:0
返回 x 在y 中第一次出现处的索引值为:-1
x包含y