java 獲取倒數第幾個字符出現的位置

一、問題說明

現在有一個字符串"com.kittycoder.StudentMapper.selectAllStudent"(mybatis中帶全路徑的sqlId,變量名爲str)

我現在需要把這個字符串轉換成"StudentMapper.selectAllStudent"

思路:先找到str的倒數第一個"."的位置(lastIndex),然後再基於倒數第一個"."的位置找到倒數第二個"."的位置(lastSecondIndex),最後截取從索引lastSecondIndex到最後一個字符的部分

代碼如下:

public class StringUtilsTest {

    // 查找字符串出現的位置
    @Test
    public void testLastOrdinalIndexOf() {
        String str = "com.kittycoder.StudentMapper.selectAllStudent"; // mybatis中帶全路徑的sqlId
        // 查找倒數第二個“.”出現的位置
        System.out.println(getSimpleSqlId2(str)); // StudentMapper.selectAllStudent
    }

    // 自己簡單寫的:獲取倒數第二個“.”
    public static String getSimpleSqlId2(String orginalSqlId) {
        int lastIndex = orginalSqlId.lastIndexOf(".");
        int lastSecondIndex = orginalSqlId.lastIndexOf(".", lastIndex - 1);
        return orginalSqlId.substring(lastSecondIndex + 1);
    }
}

後面想了下,這個需求應該有框架已經實現了,找了下common-lang3,發現可以使用lastOrdinalIndexOf

 

二、解決

public class StringUtilsTest {

    // 查找字符串出現的位置
    @Test
    public void testLastOrdinalIndexOf() {
        String str = "com.kittycoder.StudentMapper.selectAllStudent"; // mybatis中帶全路徑的sqlId
        // 查找倒數第二個“.”出現的位置
        System.out.println(getSimpleSqlId(str)); // StudentMapper.selectAllStudent
    }

    // 獲取簡單的sqlId(使用工具類)
    public static String getSimpleSqlId(String orginalSqlId) {
        if (StringUtils.isNotBlank(orginalSqlId)) {
            // 獲取倒數第二個“.”
            int dotPos = StringUtils.lastOrdinalIndexOf(orginalSqlId, ".", 2);
            if (dotPos == -1) {
                return "";
            } else {
                return orginalSqlId.substring(dotPos + 1);
            }
        }
        return "";
    }
}

參考鏈接:https://www.cnblogs.com/chenghu/p/3179369.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章