判斷一個字元串是否包含某個子串的n種方法
- startsWith()
- contains方法
- indexOf方法
這個方法有兩個變體并測試如果一個字元串開頭的指定索引指定的字首或在預設情況下從字元串開始位置
此方法定義的文法如下:
public boolean startsWith(String prefix, int toffset)
or
public boolean startsWith(String prefix)
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) );
}
}
java.lang.String.contains()
方法傳回true,當且僅當此字元串包含指定的char值序列
public static void main(String[] args) {
String str = "abc";
boolean status = str.contains("a");
if(status){
System.out.println("包含");
}else{
System.out.println("不包含");
}
}
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);
}
}