Java 字符串包含 String contains() 示例代码

在Java的字符串包含搜索给定字符串中的子字符串。如果传入的字符串在此给定字符串中,它返回true;否则,返回false。

字符串 contains() 方法

使用 String 的 contains()要找到一个字符串出现在给定的字符串或没有。请记住,此方法区分大小写

/**
* @param substring - substring to be searched in this string
* 
* @return - true if substring is found,
*           false if substring is not found
*/
public boolean contains(CharSequence substring) {
    return indexOf(s.toString()) > -1;
}

该方法内部借助 indexOf() 方法来检查子字符串的索引。如果存在子字符串,则索引将始终大于’0’。

入参不能为 null

String 的 contains()方法不接受null参数。如果方法参数为null,它将抛出 NullPointerException。

Exception in thread “main” java.lang.NullPointerException
at java.lang.String.contains(String.java:2120)
at com.StringExample.main(StringExample.java:7)

字符串 contains() 示例

public class StringContains {
    public static void main(String[] args) {
        System.out.println("Hello World".contains("Hello"));
        System.out.println("Hello World".contains("hello"));
        System.out.println("Hello World".contains("Hi"));
        System.out.println("Hello World".contains(""));
    }
}
true
false
false
true

使用 Java 字符串 contains() 方法检查给定字符串中是否存在子字符串。

标签: