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

如题所述

方法:

使用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"
温馨提示:答案为网友推荐,仅供参考
第1个回答  2017-05-27

使用contains方法即可

String s = "abcd";
s.contains("bc");

第2个回答  2017-05-27
indexOf 也可以判断了

~
~
~
相似回答