字符串contains()
方法的语法为:
string.contains(CharSequence ch)
在这里, 字符串是String
类的对象。
contains()参数
contains()
方法采用单个参数。
- ch (charSequence)- 字符序列
注意: charSequence
是字符序列,例如:String,CharBuffer,StringBuffer等。
contains()返回值
- 如果字符串包含指定的
ch
则返回true - 如果字符串不包含指定的
ch
则返回false
示例1:Java字符串contains()
class Main {
public static void main(String[] args) {
String str1 = "Learn Java";
Boolean result;
// check if str1 contains "Java"
result = str1.contains("Java");
System.out.println(result); // true
// check if str1 contains "Python"
result = str1.contains("Python");
System.out.println(result); // false
// check if str1 contains ""
result = str1.contains("");
System.out.println(result); // true
}
}
在这里, str.contains("")
给出true
因为空字符串是其他所有字符串的子集。
示例2:将contains()与if … else一起使用
class Main {
public static void main(String[] args) {
String str1 = "Learn Java";
String str2 = "Java";
String str3 = "java";
Boolean result;
// true because "Learn Java" contains "Java"
if (str1.contains(str2)) {
System.out.println(str1 + " contains " + str2);
}
else {
System.out.println(str1 + " doesn't contains " + str2);
}
// contains() is case-sensitive
// false because "Learn Java" doesn't contains "ava"
if (str1.contains(str3)) {
System.out.println(str1 + " contains " + str3);
}
else {
System.out.println(str1 + " doesn't contain " + str3);
}
}
}
输出
Learn Java contains Java
Learn Java doesn't contain java