欢迎访问宙启技术站
智能推送

contains()函数说明

发布时间:2023-06-10 19:35:13

contains()函数是一种常用的字符串函数,在Java中可以用于判断一个字符串是否包含另一个字符串。它可以帮助我们快速地检查字符串中是否包含特定的字符序列,如果包含,则返回true,否则返回false。这个函数非常简单易懂,适合各类程序员使用。

contains()语法:

public boolean contains(CharSequence sequence)

参数说明:

- sequence:需要查找的序列

返回值说明:

- 如果字符串包含sequence,则返回true,否则返回false

下面是contains()函数的使用示例:

public class ContainsExample {
    public static void main(String[] args) {
        String text = "Hello World";
        System.out.println(text.contains("Hello"));   // true
        System.out.println(text.contains("World"));   // true
        System.out.println(text.contains("world"));   // false
        System.out.println(text.contains("llo W"));   // true
        System.out.println(text.contains("Java"));    // false
    }
}

以上代码的输出结果为:

true
true
false
true
false

从以上示例中可以看出,contains()函数非常简单易用,它可以帮助我们快速地检查字符串中是否包含特定的字符序列。下面我们来看一下contains()函数的更多用法和注意事项。

1. contains()函数区分大小写

contains()函数在判断是否包含特定的字符串时,是区分大小写的。所以如果你需要不区分大小写地检查字符串,需要在使用contains()函数之前先将字符串转换为小写或大写:

public class ContainsExample {
    public static void main(String[] args) {
        String text = "Hello World";
        System.out.println(text.contains("World"));   // true
        System.out.println(text.contains("world"));   // false

        text = text.toLowerCase();
        System.out.println(text.contains("world"));   // true
    }
}

以上代码的输出结果为:

true
false
true

2. contains()函数支持正则表达式

contains()函数也支持使用正则表达式作为参数。这个特性可以帮助我们在更复杂的字符串中查找特定的字符序列。

public class ContainsExample {
    public static void main(String[] args) {
        String text = "Hello World!";
        System.out.println(text.contains("\\w+"));   // true
    }
}

以上代码的输出结果为true。这是因为正则表达式“\w+”可以匹配字符串中的所有单词,包括“Hello”和“World”。

3. contains()函数无法处理null值

contains()函数在处理null值时会抛出NullPointerException异常,因此在使用contains()函数时,需要先判断字符串是否为null:

public class ContainsExample {
    public static void main(String[] args) {
        String text1 = null;
        String text2 = "Hello World!";
        System.out.println(text1 != null && text1.contains("Hello"));   // false
        System.out.println(text2 != null && text2.contains("Hello"));   // true
    }
}

以上代码的输出结果为:false和true,因为text1为null,所以调用contains()函数会抛出异常。

总结

contains()函数是一种常用的字符串函数,它可以帮助我们快速地检查字符串中是否包含特定的字符序列。我们使用contains()函数前需要注意以下几点:

- contains()函数在判断是否包含特定的字符串时,是区分大小写的,如果需要不区分大小写地检查字符串,需要先将字符串转换为小写或大写

- contains()函数也支持使用正则表达式作为参数,这个特性可以帮助我们在更复杂的字符串中查找特定的字符序列

- contains()函数在处理null值时会抛出NullPointerException异常,因此在使用contains()函数时,需要先判断字符串是否为null