Java中字符串中子串的查找共有四種方法,如下:
1、int indexOf(String str) :返回第一次出現的指定子字符串在此字符串中的索引。
2、int indexOf(String str, int startIndex):從指定的索引處開始,返回第一次出現的指定子字符串在此字符串中的索引。
3、int lastIndexOf(String str) :返回在此字符串中最右邊出現的指定子字符串的索引。
4、int lastIndexOf(String str, int startIndex) :從指定的索引處開始向后搜索,返回在此字符串中最后一次出現的指定子字符串的索引。
public class Test {
public static void main(String[] args) {
String s = "xXccxxxXX";
// 從頭開始查找是否存在指定的字符 //結果如下
System.out.println(s.indexOf("c")); //2
// 從第四個字符位置開始往后繼續查找,包含當前位置
System.out.println(s.indexOf("c", 3)); //3
//若指定字符串中沒有該字符則系統返回-1
System.out.println(s.indexOf("y")); //-1
System.out.println(s.lastIndexOf("x")); //6
System.out.println(s.indexOf(120,2)); //4
System.out.println(s.indexOf('x',2)); //4 120是x的ASCII編碼
}
}
補充一點 如果對要查找的字符有特殊規則要求 可以用正則表達式解決
摘抄自http://blog.csdn.net/qq_27093465/article/details/51832189
