2021-12-27 Java String contains() 方法用于判断字符串中是否包含指定的字符或字符串。用.toLowerCase().contains忽视大小写。传入null 空会报错

本文详细介绍了Java中String类的contains()方法,该方法用于检查字符串是否包含特定的字符或子字符串。通过示例代码展示了如何使用contains(),并给出了测试结果。文章还提供了参考资料链接,供读者深入学习。

一、public boolean contains(CharSequence chars)

       contains() 方法用于判断字符串中是否包含指定的字符或字符串。

二、返回值
       如果包含指定的字符或字符串返回 true,否则返回 false。

三、实例测试

      1、测试java 源码 

package com.giada.lib;

import java.lang.*;

public class MyClass {

    public static void main(String[] args) {

        String str1 = "read the fuck the code", str2 = "http://";

        CharSequence cs1 = "int";

        // string contains the specified sequence of char values
        boolean retval = str1.contains(cs1);
        System.out.println("Method returns : " + retval);

        retval = str1.contains("fuck");
        System.out.println("fuck Method returns : " + retval);

        // string does not contain the specified sequence of char value
        retval = str2.contains("_");
        System.out.println("Methods returns: " + retval);
    }
}

      2、运行结果

三、传入null 空会报错、

IndexActivity: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toLowerCa
se()' on a null object reference

 应该用下面代码判断字符串是否是为空

if(s == null || s.length() == 0);

四、参考文章

Java String contains() 方法 | 菜鸟教程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值