今天,我们通过indexOf和lastIndexOf方法,来查找字符和字符串的位置。
具体方法描述如下:(来自菜鸟教程)
本段代码定义的字符串的位置说明。
h | t | t | p | s | : | / | / | w | w | w | . | c | s | d | n | . | n | e | t | . | c | s | d | n | . | n | e | t | / |
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 |
具体代码、注释和运行结果如下:
public class SearchString {
public static void main(String args[]) {
String Str1 = "https://www.csdn.net.csdn.net/" ;
String Str2 = "csdn",Str3 = "net" ;
System.out.println("n第一次的位置:"+ Str1.indexOf( "n" ) ) ;
//第一位以0开始计算,比如abcd的顺序是0123
System.out.println("n最后的位置:" + Str1.lastIndexOf( "n" ) ) ;
System.out.println("字符串Str2【"+ Str2 +"】最后的位置:" + Str1.lastIndexOf( Str2 ) ) ;
System.out.println("从第16个位置开始,n第一次的位置:" + Str1.indexOf( "n", 16 ) ) ;
//虽然从10开始,但是返回值依然是从开始计算
System.out.println("从第15个位置开始,字符串Str2【" + Str2 +"】第一次的位置:" + Str1.indexOf( Str2, 15 )) ;
System.out.println("字符串Str3【"+ Str3 +"】最后的位置:" + Str1.lastIndexOf( Str3 )) ;
}
}
/*
运行结果如下:
n第一次的位置:15
n最后的位置:26
字符串Str2【csdn】最后的位置:21
从第16个位置开始,n第一次的位置:17
从第15个位置开始,字符串Str2【csdn】第一次的位置:21
字符串Str3【net】最后的位置:26
*/
当找不到该字符时,返回-1,可以加个if判断
public class Test2 {
public static void main(String args[]) {
String Str1 = "https://www.csdn.net/" ;
String Str2="com";
int Result1=Str1.lastIndexOf( Str2 );
if (Result1==-1) {
//当找不到该字符时,返回-1
System.out.println("没有找到该字符!");
}
else {
System.out.println("字符串Str2【"+Str2+"】的位置:" + Result1);
}
}
}