判斷一個字符串是否包含某個子串的n種方法
- startsWith()
- contains方法
- indexOf方法
startsWith()
這個方法有兩個變體並測試如果一個字符串開頭的指定索引指定的前綴或在默認情況下從字符串開始位置
此方法定義的語法如下:
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) );
}
}
contains方法
java.lang.String.contains() 方法返回true,當且僅當此字符串包含指定的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() 的用途是在一個字符串中尋找一個字的位置,同時也可以判斷一個字符串中是否包含某個字符
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);
}
}