如何搜索指定子字串的最後一次出現?

如何搜索指定子字串的最後一次出現的位置?

此示例顯示如何使用strOrig.lastIndexOf(Stringname)方法確定指定子字串在字串內的最後出現位置。

package com.zaixian;

public class SearchlastString {
    public static void main(String[] args) {
        String strOrig = "Hello world ,Hello Reader,Hello Sukida";
        int lastIndex = strOrig.lastIndexOf("Hello");

        if (lastIndex == -1) {
            System.out.println("Hello not found");
        } else {
            System.out.println("Last occurrence of Hello is at index "
                    + lastIndex);
        }
    }
}

執行上示例代碼,得到以下結果 -

Last occurrence of Hello is at index 26

示例

下麵示例顯示了如何使用strOrig.lastIndexOf(Stringname)方法來確定指定子字串在字串中最後出現的位置。

package com.zaixian;

public class SearchlastString2 {
    public static void main(String[] args) {
        String t1 = "Welcome to xuhuhu.com";
        int index = t1.lastIndexOf("o");
        System.out.println("Found last index is: "+index);
    }
}

執行上示例代碼,得到以下結果 -

Found last index is: 19

上一篇: Java字串 下一篇: Java數組