java中怎么判断一个字符串中包含某个字符或字符串

Python027

java中怎么判断一个字符串中包含某个字符或字符串,第1张

方法

使用String类的indexOf()方法可以判断一个字符串是否在另一个字符串中出现,其方法原型为:

int java.lang.String.indexOf(String arg0)

如果字符串arg0出现在源字符串中,返回arg0在源字符串中首次出现的位置。

Java程序:

public class Main { 

    public static void main(String[] args) {

        String key = "wo"

        char[] arr = {'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!'}

        String source= String.valueOf(arr)

         

        if(source.indexOf(key) >= 0) {

            System.out.printf("\"%s\" 中包含 \"%s\"", source, key)

        }

        else {

            System.out.printf("\"%s\" 中不包含 \"%s\"", source, key)

        }

    }

}

运行测试:

"Hello, world!" 中包含 "wo"

一般用 indexOf() 函数就可以, 如果字符存在于字符串中则返回大于0的值

String str = "abc"

System.out.println(str.indexOf("a"))

输出的就是 0 ,如果不存在则返回 -1