java判斷字串包含某個字元的例項方法
阿新 • • 發佈:2020-01-07
java判斷字串是否包含某個字元的方法:
一、contains方法
1:描述
java.lang.String.contains() 方法返回true,當且僅當此字串包含指定的char值序列
2:宣告
public boolean contains(CharSequence s)
3:返回值
如果此字串包含返回true,否則返回false。
4:例項
public static void main(String[] args) { String str = "abc"; boolean status = str.contains("a"); if(status){ System.out.println("包含"); }else{ System.out.println("不包含"); } }
二、indexOf方法
1:描述
java.lang.String.indexOf() 的用途是在一個字串中尋找一個字的位置,同時也可以判斷一個字串中是否包含某個字元。
2:宣告
int indexOf(int ch,int fromIndex)
3:返回值
indexOf的返回值為int
4:例項
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判斷字串是否包含某個字元的方法的詳細內容,感謝大家的學習和對我們的支援。