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

你可能感兴趣的:(java,java,工具方法)