一、問題說明
現在有一個字符串"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 "";
}
}