查找字符串最后一次出现的位置(java)

以下实例中我们通过字符串函数 strOrig.lastIndexOf(Stringname) 来查找子字符串 Stringname 在 strOrig 出现的位置:

public class SearchlastString {
   public static void main(String[] args) {
      String strOrig = "Hello world ,Hello Runoob";
      int lastIndex = strOrig.lastIndexOf("Runoob");
      if(lastIndex == - 1){
         System.out.println("没有找到字符串 Runoob");
      }else{
         System.out.println("Runoob 字符串最后出现的位置: "+ lastIndex);
      }
   }
}
输出结果:Runoob 字符串最后出现的位置: 19

public int lastIndexOf(int ch)//ch -- 字符

public int lastIndexOf(int ch, int fromIndex)//fromIndex -- 开始搜索的索引位置

public int lastIndexOf(String str)//str -- 要搜索的子字符串

public int lastIndexOf(String str, int fromIndex)
例子:

public class Test {
    public static void main(String args[]) {
        String Str = new String("菜鸟教程:www.runoob.com");
        String SubStr1 = new String("runoob");
        String SubStr2 = new String("com");

        System.out.print("查找字符 o 最后出现的位置 :" );
        System.out.println(Str.lastIndexOf( 'o' ));
        System.out.print("从第14个位置查找字符 o 最后出现的位置 :" );
        System.out.println(Str.lastIndexOf( 'o', 14 ));
        System.out.print("子字符串 SubStr1 最后出现的位置:" );
        System.out.println( Str.lastIndexOf( SubStr1 ));
        System.out.print("从第十五个位置开始搜索子字符串 SubStr1最后出现的位置 :" );
        System.out.println( Str.lastIndexOf( SubStr1, 15 ));
        System.out.print("子字符串 SubStr2 最后出现的位置 :" );
        System.out.println(Str.lastIndexOf( SubStr2 ));
    }
}

输出结果:
查找字符 o 最后出现的位置 :17
从第14个位置查找字符 o 最后出现的位置 :13
子字符串 SubStr1 最后出现的位置:9
从第十五个位置开始搜索子字符串 SubStr1最后出现的位置 :9
子字符串 SubStr2 最后出现的位置 :16

猜你喜欢

转载自blog.csdn.net/qq_36330733/article/details/86535550