原文: https://beginnersbook.com/2017/10/java-string-contains-method/

Java String contains()方法检查特定字符序列是否是给定字符串的一部分。如果给定字符串中存在指定的字符序列,则此方法返回true,否则返回false

例如:

  1. String str = "Game of Thrones";
  2. //This will print "true" because "Game" is present in the given String
  3. System.out.println(str.contains("Game"));
  4. /* This will print "false" because "aGme" is not present, the characters
  5. * must be present in the same sequence as specified in the contains method
  6. */
  7. System.out.println(str.contains("aGme"));

contains()方法的语法

  1. public boolean contains(CharSequence str)

返回类型是boolean,这意味着此方法返回truefalse。当在给定字符串中找到字符序列时,此方法返回true,否则返回false

如果CharSequencenull,则此方法抛出NullPointerException
例如:像这样调用此方法会抛出NullPointerException

  1. str.contains(null);

Java String contains()方法示例

第二个print语句显示为false,因为contains()方法区分大小写。 您也可以使用contains()方法进行不区分大小写的检查,我已经在本教程末尾介绍了。

  1. class Example{
  2. public static void main(String args[]){
  3. String str = "Do you like watching Game of Thrones";
  4. System.out.println(str.contains("like"));
  5. /* this will print false as the contains() method is
  6. * case sensitive. Here we have mentioned letter "l"
  7. * in upper case and in the actual string we have this
  8. * letter in the lower case.
  9. */
  10. System.out.println(str.contains("Like"));
  11. System.out.println(str.contains("Game"));
  12. System.out.println(str.contains("Game of"));
  13. }
  14. }

输出:

  1. true
  2. false
  3. true
  4. true

示例 2:在if-else语句中使用 Java String contains()方法

我们知道contains()方法返回一个布尔值,我们可以将此方法用作if-else语句中的条件。

  1. class JavaExample{
  2. public static void main(String args[]){
  3. String str = "This is an example of contains()";
  4. /* Using the contains() method in the if-else statement, since
  5. * this method returns the boolean value, it can be used
  6. * as a condition in if-else
  7. */
  8. if(str.contains("example")){
  9. System.out.println("The word example is found in given string");
  10. }
  11. else{
  12. System.out.println("The word example is not found in the string");
  13. }
  14. }
  15. }

输出:

Java `String contains()`方法 - 图1

Java String contains()方法,用于不区分大小写的检查

我们在上面已经看到contains()方法区分大小写,但是通过一个小技巧,您可以使用此方法进行不区分大小写的检查。让我们举个例子来理解这个:

这里我们使用toLowerCase()方法将两个字符串转换为小写,以便我们可以使用contains()方法执行不区分大小写的检查。我们也可以使用toUpperCase()方法实现同样的目的,如下例所示。

  1. class Example{
  2. public static void main(String args[]){
  3. String str = "Just a Simple STRING";
  4. String str2 = "string";
  5. //Converting both the strings to lower case for case insensitive checking
  6. System.out.println(str.toLowerCase().contains(str2.toLowerCase()));
  7. //You can also use the upper case method for the same purpose.
  8. System.out.println(str.toUpperCase().contains(str2.toUpperCase()));
  9. }
  10. }

输出:

  1. true
  2. true

参考:

String Contains()方法 JavaDoc)