You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java字符串截取:跳过最后两个分隔符的高效简洁实现方案

优化路径字符串处理的简洁高效实现

嘿,我来帮你优化这段路径处理代码——原代码反复调用substring和lastIndexOf,还创建了好几个中间字符串,既啰嗦又有额外的对象开销。我们可以通过一次性定位关键斜杠位置的方式,简化代码逻辑同时提升执行效率,避免不必要的字符串对象创建和重复遍历。

优化后的代码

public static void main(String[] args) {
    String path = "/abc/def/ghi/jkl/mno/qqq.xml";
    
    // 依次定位倒数第一、第二、第三个斜杠的位置
    int lastSlash = path.lastIndexOf('/');
    int secondLastSlash = path.lastIndexOf('/', lastSlash - 1);
    int thirdLastSlash = path.lastIndexOf('/', secondLastSlash - 1);
    
    // 直接截取目标子串,无需中间变量
    String lastSegment = path.substring(lastSlash + 1);
    String prefixWithoutLastTwo = path.substring(0, thirdLastSlash);
    
    System.out.println(lastSegment);
    System.out.println(prefixWithoutLastTwo);
}

为什么这个实现更好?

  • 更少的对象创建:原代码生成了first、first1两个中间字符串,优化后的代码完全避免了这些额外的内存开销。
  • 更快的查找效率:每次调用lastIndexOf时都指定了查找的结束位置(比如lastSlash - 1),让方法只在需要的范围内遍历字符串,而不是从开头重新扫描。
  • 逻辑更清晰:直接定位到我们需要的三个斜杠位置,一步到位截取目标子串,代码意图一目了然。

可选的边界情况处理

如果需要兼容路径格式不合法的情况(比如斜杠数量不足3个),可以添加简单的校验避免异常:

public static void main(String[] args) {
    String path = "/abc/def/ghi/jkl/mno/qqq.xml";
    
    int lastSlash = path.lastIndexOf('/');
    if (lastSlash == -1) {
        handleInvalidPath();
        return;
    }
    
    int secondLastSlash = path.lastIndexOf('/', lastSlash - 1);
    if (secondLastSlash == -1) {
        handleInvalidPath();
        return;
    }
    
    int thirdLastSlash = path.lastIndexOf('/', secondLastSlash - 1);
    if (thirdLastSlash == -1) {
        handleInvalidPath();
        return;
    }
    
    String lastSegment = path.substring(lastSlash + 1);
    String prefixWithoutLastTwo = path.substring(0, thirdLastSlash);
    
    System.out.println(lastSegment);
    System.out.println(prefixWithoutLastTwo);
}

private static void handleInvalidPath() {
    System.out.println("路径格式不符合要求,无法截取目标子串");
}

内容的提问来源于stack exchange,提问作者Ramiz Raza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:53:10