1. 概述

本文将探讨在Java中移除字符串最后一个字符的多种实现方式。这些方法各有特点,适用于不同场景,我们将逐一分析其优缺点及适用边界。

2. 使用String.substring()

最直接的方式是使用String类内置的substring()方法。通过指定起始索引(0)和结束索引(字符串长度-1)即可截取目标子串:

public static String removeLastChar(String s) {
    return (s == null || s.length() == 0)
      ? null 
      : (s.substring(0, s.length() - 1));
}

关键点:

  • ✅ 代码简洁直观
  • ❌ 非null安全,空字符串会抛异常
  • ⚠️ 需手动处理边界条件

使用Java 8的Optional改进版本:

public static String removeLastCharOptional(String s) {
    return Optional.ofNullable(s)
      .filter(str -> str.length() != 0)
      .map(str -> str.substring(0, str.length() - 1))
      .orElse(s);
}

3. 使用StringUtils.substring()

Apache Commons Lang3库提供的StringUtils类包含更健壮的字符串操作方法。首先添加依赖:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

核心实现:

String TEST_STRING = "abcdef";
StringUtils.substring(TEST_STRING, 0, TEST_STRING.length() - 1);

特性对比: | 特性 | 原生substring | StringUtils.substring | |---------------|---------------|-----------------------| | null安全 | ❌ | ✅ | | 空字符串处理 | ❌ | ✅ | | 代码复杂度 | 低 | 中(需引入依赖) |

4. 使用StringUtils.chop()

StringUtils.chop()是专门为移除末尾字符设计的方法,完美处理所有边界情况:

StringUtils.chop(TEST_STRING);

优势:

  • ✅ 天然null安全
  • ✅ 自动处理空字符串
  • ✅ 单一职责,语义清晰
  • ⚠️ 仅适用于移除单个字符场景

5. 使用正则表达式

通过正则表达式匹配末尾字符并替换为空字符串:

public static String removeLastCharRegex(String s) {
    return (s == null) ? null : s.replaceAll(".$", "");
}

Java 8优化版:

public static String removeLastCharRegexOptional(String s) {
    return Optional.ofNullable(s)
      .map(str -> str.replaceAll(".$", ""))
      .orElse(s);
}

注意事项:

  • ⚠️ 正则.$匹配除换行符外的任意字符
  • ❌ 字符串以换行结尾时失效
  • ✅ 灵活可扩展(如修改正则移除多个字符)

6. 总结

方法 null安全 空字符串处理 灵活性 依赖
substring()
Optional+substring
StringUtils.substring Apache
StringUtils.chop() Apache
正则表达式

选择建议:

  1. 简单场景:原生substring()(确保非null)
  2. 通用场景:StringUtils.chop()(最省心)
  3. 复杂场景:正则表达式(需处理换行等特殊情况)
  4. 避免重复造轮子:优先使用成熟库方法

💡 经验之谈:生产环境中,Apache Commons Lang的方案能减少80%的边界条件检查,但要注意引入依赖的权衡。


原始标题:How to Remove the Last Character of a String?