您好,登錄后才能下訂單哦!
java怎么判斷字符串是否包含指定字符?針對(duì)這個(gè)問題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡(jiǎn)單易行的方法。
1、startsWith()
這個(gè)方法有兩個(gè)變體并測(cè)試如果一個(gè)字符串開頭的指定索引指定的前綴或在默認(rèn)情況下從字符串開始位置
此方法定義的語法如下:
public boolean startsWith(String prefix, int toffset) or public boolean startsWith(String prefix)
prefix – 要匹配的前綴。這里是參數(shù)的細(xì)節(jié):
toffset – 從哪里開始尋找字符串。
返回值為true和false
import java.io.*; public class Test{ public static void main(String args[]){ String Str = new String("Welcome to Yiibai.com"); System.out.print("Return Value :" ); System.out.println(Str.startsWith("Welcome") ); System.out.print("Return Value :" ); System.out.println(Str.startsWith("Tutorials") ); System.out.print("Return Value :" ); System.out.println(Str.startsWith("Yiibai", 11) ); } }
2、contains方法
java.lang.String.contains()
方法返回true,當(dāng)且僅當(dāng)此字符串包含指定的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("不包含"); } }
3、indexOf方法
java.lang.String.indexOf() 的用途是在一個(gè)字符串中尋找一個(gè)字的位置,同時(shí)也可以判斷一個(gè)字符串中是否包含某個(gè)字符
indexOf的返回值為int
public static void main(String[] args) { String str1 = "abcdefg"; int result1 = str1.indexOf("ab"); if(result1 != -1){ System.out.println("字符串str中包含子串“ab”"+result1); }else{ System.out.println("字符串str中不包含子串“ab”"+result1); } }
關(guān)于java怎么判斷字符串是否包含指定字符問題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識(shí)。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。