java中的lastIndexOf( )函数是什么意思

String中的lastIndexOf方法,是获取要搜索的字符字符串最后次出现的位置。

可以看到有四个重载方法分别是:

    public int lastIndexOf(int ch);
    public int lastIndexOf(int ch, int fromIndex);
    public int lastIndexOf(String str);
    public int lastIndexOf(String str, int fromIndex);

四个方法,其中第一、第二个方法时对char(字符)进行匹配,区别在于第二个方法多了个参数 fromIndex,该参数的含义是从String(字符串)中的第几位开始向前进行匹配。

同理第三个和第四个方法时对字符串进行匹配,第四个方法可以申明开始向前匹配的位置。

示例1如下:

public class Test {
    public static void main(String[] args) {
        String str = "sdasaq";
        System.out.println(str.lastIndexOf('a'));        // 4
        System.out.println(str.lastIndexOf('a', 3));     // 2
        System.out.println(str.lastIndexOf("as"));       // 2
        System.out.println(str.lastIndexOf("as", 1));    // 1    
    }
}

示例2如下:

  int x = a.lastIndexOf(b); // 表示b字符串在a字符串中最后出现的位置。从0开始。

  如:a= "abcdabcd"; b="d";  那么x的值为7

示例3如下:

  指定字符串最后出现的位置,从0开始:
  System.out.println("abcde".lastIndexOf("c"));  // 输出2
  System.out.println("abcdec".lastIndexOf("c")); // 输出5

猜你喜欢

转载自www.cnblogs.com/chenmingjun/p/9862468.html