java判断字符串是否含有指定字符的方法

内容摘要
java判断字符串是否含有指定字符的方法:1、使用contains方法判断当且仅当此字符串包含指定的char值序列,java.lang.String.contains() 方法返回true。声明:public boolean cont
文章正文

java判断字符串是否含有指定字符的方法:

1、使用contains方法判断

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

声明:public boolean contains(CharSequence s)

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

示例:

1
2
3
4
5
6
7
8
9
public static void main(String[] args) { 
        String str = "abc"
        boolean status = str.contains("a"); 
        if(status){ 
            System.out.println("包含"); 
        }else
            System.out.println("不包含"); 
        
    }

2、使用indexOf方法判断

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

声明:int indexOf(int ch,int fromIndex)

返回值:indexOf的返回值为int

示例:

1
2
3
4
5
6
7
8
9
public static void main(String[] args) { 
    String str1 = "abcdefg"
    int result1 = str1.indexOf("a"); 
    if(result1 != -1){ 
        System.out.println("字符串str中包含子串“a”"+result1); 
    }else
        System.out.println("字符串str中不包含子串“a”"+result1); 
    
}

更多java知识请关注java基础教程栏目。

代码注释
[!--zhushi--]

作者:喵哥笔记

IDC笔记

学的不仅是技术,更是梦想!