最近在使用String中的lastIndexOf(String str, int fromIndex)方法的时候,发现有时候的返回值与我们想要的结果不一样,在这里进行记录。
问题:返回String str = "helloworld"
中“llo”字符存在的索引位置,使用lastIndexOf()
或者Indexof()
方法。
public void test1() {
String str = "helloworld";
// 1. int indexOf(String str): 返回指定子字符串在此字符串中第一次出现处的索引
int i1 = str.indexOf("llo");
int i2 = str.indexOf("lloo"); // 如果找不到,则返回-1
System.out.println(i1);
System.out.println(i2);
System.out.println("--------------------------------");
// 2. int indexOf(String str, int fromIndex): 返回指定子字符串在此字符中第一此出现处的索引,从指定的索引开始
int i3 = str.indexOf("llo", 2);
int i4 = str.indexOf("llo", 4); // 如果找不到,则返回-1
System.out.println(i3);
System.out.println(i4);
System.out.println("--------------------------------");
// 3. int lastIndexOf(String str): 返回指定子字符串在此字符串最后边出现处的索引
int i5 = str.lastIndexOf("llo");
System.out.println(i5);
System.out.println("--------------------------------");
// 4. int lastIndexOf(String str, int fromIndex): 返回指定子字符串在此字符串中最后一次出现处的索引,**从指定的索引开始返向(左)搜索**。
String str2 = "hellorworld";
int i6 = str2.lastIndexOf("or", 6);
int i7 = str2.lastIndexOf("or", 3);
System.out.println("str = " + str2 + ", str.sunstr(0, 4) = " + str2.substring(0, 4));
int i8 = str2.substring(0, 4).lastIndexOf("llo", 3);
System.out.println(i6);
System.out.println(i7);
System.out.println(i8);
System.out.println("--------------------------------");
System.out.println(new String("helloworld").lastIndexOf("llo", 0)); // -1
System.out.println(new String("helloworld").lastIndexOf("llo", 1)); // -1
// note: 下面会输出2,可能是因为此时我们从索引2开始,helloworld的索引2为l,与"llo"的第一个元素相同,此时会继续往后(右边)寻找,知道匹配完成
System.out.println(new String("helloworld").lastIndexOf("llo", 2)); // 2
System.out.println(new String("hellworllod").lastIndexOf("llo", 3)); // -1
System.out.println(new String("helloworllod").lastIndexOf("llo", 3)); // 2
}
note: 我们可以观察到在new String("helloworld").lastIndexOf("llo", 2))
中将会返回2,而按照我们正常的思路,此时程序将会从索引2开始向左查找,应该是返回-1。这里我的解释是:此时我们从索引2开始,helloworld的索引2为l,与"llo"的第一个元素相同,此时会继续往后(右边)寻找,直到匹配完成或找不到后会继续向左查找。