
java判斷字元串是否含有指定字元的方法:
1、使用contains方法判斷
當且僅當此字元串包含指定的char值序列,java.lang.String.contains() 方法傳回true。
聲明:public boolean contains(CharSequence s)
傳回值:此方法傳回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("不包含");
}
}
2、使用indexOf方法判斷
java.lang.String.indexOf() 的用途是在一個字元串中尋找一個字的位置,同時也可以判斷一個字元串中是否包含某個字元。
聲明:int indexOf(int ch,int fromIndex)
傳回值:indexOf的傳回值為int
示例: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基礎教程欄目。