使用了 String 類的 indexOf() 方法在字符串中查找子字符串出現的位置,如過存在返回字符串出現的位置(第一位為0),如果不存在返回 -1。方便判斷和截取字符串!
語法:stringObject.indexOf(searchvalue,fromindex)
參數描述
searchvalue 必需。規定需檢索的字符串值。
fromindex 可選的整數參數。規定在字符串中開始檢索的位置。它的合法取值是0到 - 1。如省略該參數,則將從字符串的首字符開始檢索。
該方法將從頭到尾地檢索字符串 stringObject,看它是否含有子串 searchvalue。開始檢索的位置在字符串的 fromindex 處或字符串的開頭(沒有指定 fromindex 時)。如果找到一個 searchvalue,則返回 searchvalue 的第一次出現的位置。stringObject 中的字符位置是從 0 開始的。
注釋:indexOf() 方法對大小寫敏感!
注釋:如果要檢索的字符串值沒有出現,則該方法返回 -1。
示例:
public class SearchStringEmp {
public static void main(String[] args) {
String strOrig = "Hello World!Hello World!";
int intIndex = strOrig.indexOf("Hello");
if(intIndex == - 1){
System.out.println("沒有找到字符串 Hello");
}else{
System.out.println("Hello 字符串位置:" + intIndex);
}
}
}
結果:
Hello 字符串位置: 0
注釋:當字符串中多次出現相同的字符串時,此方法返回的值為第一次出現的位置的索引值。
lastIndexOf(Stringname):
我們可以通過lastIndexOf(Stringname)來查找子字符串 Stringname 在 字符串中最后出現的位置
示例:
public class SearchlastString {
public static void main(String[] args) {
String str = "Hello world!Hello World!";
int lastIndex = str.lastIndexOf("Hello");
if(lastIndex == - 1){
System.out.println("沒有找到字符串 Hello");
}else{
System.out.println("Hello 字符串最后出現的位置: "+ lastIndex);
}
}
}
結果:
Hello 字符串最后出現的位置: 12