檢索字符串,查找某個字符的位置,位置是從0開始檢索的
注意:空格也算是一個字符。
package changYongLei;
public class JianSuo_String {
public static void main(String[] args) {
String s1 = "China people countrys";
// indexOf(String(int) ch) 返回指定字符在此字符串中第一次出現處的索引。------int
System.out.println(s1.indexOf("o"));//字符‘o’第一次出現的位置索引
// indexOf(String(int) ch, int fromIndex) 返回在此字符串中第一次出現指定字符處的索引,從指定的索引開始搜索。------int
System.out.println(s1.indexOf("e",8));//無論從哪裏開始索引,返回的索引位置都是整個字符串某個字符第一次出現的索引位置
// lastIndexOf(String(int) ch) 返回指定字符在此字符串中最後一次出現處的索引。----int
System.out.println(s1.lastIndexOf("n"));//字符‘n’最後一次出現的位置索引
// lastIndexOf(String(int) str, int fromIndex) 返回指定子字符串在此字符串中最後一次出現處的索引,從指定的索引開始反向搜索。-----int
System.out.println(s1.lastIndexOf("n",17));//找到索引爲17的字符,看前面有沒有‘n’字符,反向查找,找到第一個即可,索引還是由正向開始
System.out.println(s1.lastIndexOf("n",2));//索引爲2的字符以及該索引之前的字符都沒有‘n’字符,故查找不到,返回-1
System.out.println(s1.lastIndexOf("n",5));//查找的是索引爲5之前的字符爲‘n’的索引
// charAt(int index) 返回指定索引處的 char 值-----char
// 即:返回字符串中index位置上的字符,其中index的取值範圍是:0~(字符串長度-1)
System.out.println(s1.charAt(3));
}
}
String類檢索的小測試:
判斷郵箱格式是否正確:
package changYongLei;
//判斷郵箱格式是否正確,其正確格式應爲@在.之前
//檢索字符串,查找某個字符的位置,位置是從0開始檢索的
public class JianSuoText_String {
public static void main(String[] args) {
String ID="[email protected]";
System.out.println("ID:"+ID);
int a=ID.indexOf("@");
int b=ID.indexOf(".");
System.out.println("@:"+a+"\t.:"+b);
if(a<b)
System.out.println("ID is true");
else
System.out.println("ID is false");
}
}