您好,登錄后才能下訂單哦!
判斷一個(gè)字符串是否包含某個(gè)子串的n種方法:
1、startsWith()
方法
2、contains()
方法
3、indexOf
方法
startsWith()方法
這個(gè)方法有兩個(gè)變體,用于檢測(cè)字符串是否以指定的前綴開始。
此方法定義的語(yǔ)法如下:
public boolean startsWith(String prefix, int toffset) or public boolean startsWith(String prefix)
參數(shù)說(shuō)明:
prefix
– 要匹配的前綴。
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) ); } }
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("不包含"); } }
indexOf方法
java.lang.String.indexOf()
用途是在一個(gè)字符串中尋找一個(gè)字的位置,同時(shí)也可以判斷一個(gè)字符串中是否包含某個(gè)字符。
返回值:
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); } }
以上就是java中判斷字符串中是否包含某個(gè)特定字符串的方法有哪些的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注億速云其它相關(guān)文章!
免責(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)容。