contains和indexof都可以作为判断是否包含的方法,这里用代码输出说明两者的不同,代码如下:
public class ContainOrIndexof {
public static void main(String[] args) {
String a="abcdefghijklmn";
String b="defghi";
String c="rst";
System.out.println(a.contains(b));//如果包含,contains返回true
System.out.println(a.indexOf(b));//如果包含,indexOf返回字符串匹配的首索引位置,3
System.out.println(a.contains(c));//如果不包含,contains返回false
System.out.println(a.indexOf(c));//如果不包含,indexOf返回-1
}
}
本文通过示例代码展示了Java中contains与indexOf方法的区别。contains用于判断字符串是否包含指定子串,返回布尔值;indexOf则返回子串首次出现的位置,未找到时返回-1。
1077

被折叠的 条评论
为什么被折叠?



