判断java或js中的某个字符串中是否包含有某个字符或是字符串

如题所述

在java中一般有两种方法较常用,分别是contains(String str)和indexOf(String str)。

其中contains返回值为boolean类型,true为有,false为没有;而indexOf实际上是查找一个字符串在另一个字符串的位置的一个方法,且以匹配好的第一个字符为准;所以该方法的返回值为int类型,其中 -1表示未找到,其余都是能找到意思。所以一般来讲,java中的判断方式如下:

String str = "abcde";
//第一种方法
if (str.contains("b")) {
    System.out.println("yes");
} else {
    System.out.println("no");
}

//第二种方法
if (str.indexOf("bc") >= 0) {
    System.out.println(str.indexOf("bc"));
    System.out.println("yes");
} else {
    System.out.println("no");
}

而在js中较为常见方法为indexOf(),返回值同java一样,为最常用的方法;随后,ES6又提供了三种新方法。includes(),返回布尔值,表示是否找到了参数字符串;startsWith(),返回布尔值,表示参数字符串是否在源字符串的头部;endsWith(),返回布尔值,表示参数字符串是否在源字符串的尾部。

var s = 'Hello world!';

if(s.indexOf('world')>=0){
    console.log('true');
}
if(s.includes('o')){
    console.log('true');
}
if(s.startsWith('Hello')){
    console.log('true');
}
if(s.endsWith('!')){
    console.log('true');
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2017-11-06
字符串有方法indexOf(String),可以判断的了~~~~
第2个回答  2017-11-06
用正则表达式比较好。
第3个回答  2017-11-06
示哪个目录
相似回答