在java中判断一个字符串中是否包含某个字符或字符串

一、contains方法
java.lang.String.contains() 方法返回true,当且仅当此字符串包含指定的char值序列

此方法返回true,如果此字符串包含,否则返回false。

public static void main(String[] args) {    
        String str = "abc";    
        boolean status = str.contains("a");    
        if(status){    
            System.out.println("包含");    
        }else{    
            System.out.println("不包含");    
        }    
    }   

二、indexOF方法
java.lang.String.indexOf() 的用途是在一个字符串中寻找一个字的位置,同时也可以判断一个字符串中是否包含某个字符。

public static void main(String[] args) {    
    String str1 = "abcdefg";    
    int result1 = str1.indexOf("e");    
    if(result1 != -1){    
        System.out.println("字符串str中包含子串“e”,它在字符串中的位置是:"+result1);    
    }else{    
        System.out.println("字符串str中不包含子串“e”"+result1);    
    }    
}  
发布了156 篇原创文章 · 获赞 8 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_42590334/article/details/103918509