Java String contains()方法检查特定字符序列是否是给定字符串的一部分。如果给定字符串中存在指定的字符序列,则此方法返回true,否则返回false。
例如:
String str = "Game of Thrones"; //This will print "true" because "Game" is present in the given StringSystem.out.println(str.contains("Game"));/* This will print "false" because "aGme" is not present, the characters * must be present in the same sequence as specified in the contains method */System.out.println(str.contains("aGme"));contains()方法的语法
public boolean contains(CharSequence str)
返回类型是boolean,这意味着此方法返回true或false。当在给定字符串中找到字符序列时,此方法返回true,否则返回false。
如果CharSequence为null,则此方法抛出NullPointerException。
例如:像这样调用此方法会抛出NullPointerException。
str.contains(null);
Java String contains()方法示例
第二个print语句显示为false,因为contains()方法区分大小写。 您也可以使用contains()方法进行不区分大小写的检查,我已经在本教程末尾介绍了。
class Example{ public static void main(String args[]){ String str = "Do you like watching Game of Thrones"; System.out.println(str.contains("like")); /* this will print false as the contains() method is * case sensitive. Here we have mentioned letter "l" * in upper case and in the actual string we have this * letter in the lower case. */ System.out.println(str.contains("Like")); System.out.println(str.contains("Game")); System.out.println(str.contains("Game of")); }}输出:
truefalsetruetrue
示例 2:在if-else语句中使用 Java String contains()方法
我们知道contains()方法返回一个布尔值,我们可以将此方法用作if-else语句中的条件。
class JavaExample{ public static void main(String args[]){ String str = "This is an example of contains()"; /* Using the contains() method in the if-else statement, since * this method returns the boolean value, it can be used * as a condition in if-else */ if(str.contains("example")){ System.out.println("The word example is found in given string"); } else{ System.out.println("The word example is not found in the string"); } }}输出:

Java String contains()方法,用于不区分大小写的检查
我们在上面已经看到contains()方法区分大小写,但是通过一个小技巧,您可以使用此方法进行不区分大小写的检查。让我们举个例子来理解这个:
这里我们使用toLowerCase()方法将两个字符串转换为小写,以便我们可以使用contains()方法执行不区分大小写的检查。我们也可以使用toUpperCase()方法实现同样的目的,如下例所示。
class Example{ public static void main(String args[]){ String str = "Just a Simple STRING"; String str2 = "string"; //Converting both the strings to lower case for case insensitive checking System.out.println(str.toLowerCase().contains(str2.toLowerCase())); //You can also use the upper case method for the same purpose. System.out.println(str.toUpperCase().contains(str2.toUpperCase())); }}输出:
truetrue
