1. 简介

Java 中的 String 类是开发中最常用的类之一,用于字符串的处理和操作。从 Java 11 和 Java 12 开始,String 类新增了一些实用的方法,极大增强了字符串操作的灵活性和功能性。

本文将带你快速掌握这些新增 API 的使用方式和典型应用场景。


2. indent():调整字符串缩进

indent(int n) 方法用于调整字符串中每一行的缩进。

行为说明:

  • 将字符串按行分割(使用 Java 11 新增的 lines() 方法)
  • 根据参数 n 调整每行缩进:
    • n > 0:每行前面添加 n 个空格
    • n < 0:移除最多 n 个前导空格(如果不足则全部移除)
    • n == 0:保留原样,但会统一换行符

示例代码:

@Test
public void whenPositiveArgument_thenReturnIndentedString() {
    String multilineStr = "This is\na multiline\nstring.";
    String outputStr = "   This is\n   a multiline\n   string.\n";

    String postIndent = multilineStr.indent(3);

    assertThat(postIndent, equalTo(outputStr));
}
@Test
public void whenNegativeArgument_thenReturnReducedIndentedString() {
    String multilineStr = "   This is\n   a multiline\n   string.";
    String outputStr = " This is\n a multiline\n string.\n";

    String postIndent = multilineStr.indent(-2);

    assertThat(postIndent, equalTo(outputStr));
}

3. transform():函数式字符串转换

transform(Function<? super String, ? extends R> f) 方法允许你对字符串应用一个函数,返回任意类型的结果。

优点:

  • 支持函数式编程风格
  • 可以直接链式调用
  • 返回类型不局限于字符串

示例代码:

@Test
public void whenTransformUsingLamda_thenReturnTransformedString() {
    String result = "hello".transform(input -> input + " world!");

    assertThat(result, equalTo("hello world!"));
}
@Test
public void whenTransformUsingParseInt_thenReturnInt() {
    int result = "42".transform(Integer::parseInt);

    assertThat(result, equalTo(42));
}

4. repeat():重复字符串内容

repeat(int count) 方法用于将字符串重复拼接指定次数。

规则:

  • ✅ 如果 count <= 0,返回空字符串
  • ✅ 拼接后的字符串为原字符串重复 count

示例代码:

@Test
public void whenRepeatStringTwice_thenGetStringTwice() {
    String output = "La ".repeat(2) + "Land";

    is(output).equals("La La Land");
}

5. strip():去除首尾空白字符

strip() 方法用于去除字符串首尾的空白字符(包括 Unicode 空格)。

对比:

  • strip():基于 Character.isWhitespace(),支持 Unicode 空格
  • trim():仅识别 ASCII 空格(≤ U+0020)

示例代码:

@Test
public void whenStripString_thenReturnStringWithoutWhitespaces() {
    is("\n\t  hello   \u2005".strip()).equals("hello");
}
@Test
public void whenTrimAdvanceString_thenReturnStringWithWhitespaces() {
    is("\n\t  hello   \u2005".trim()).equals("hello   \u2005");
}

6. isBlank():判断字符串是否为空白

isBlank() 方法用于判断字符串是否为空或仅包含空白字符。

注意:

  • ✅ 支持 Unicode 空格
  • ✅ 适合用于校验用户输入是否“有效”

示例代码:

@Test
public void whenBlankString_thenReturnTrue() {
    assertTrue("\n\t\u2005  ".isBlank());
}

7. lines():将字符串按行转换为 Stream

lines() 方法将字符串按行分割成一个 Stream<String>,适用于处理多行文本。

特性:

  • ✅ 自动识别换行符:\n\r\r\n
  • ✅ 每行不含换行符
  • ✅ 顺序保留

示例代码:

@Test
public void whenMultilineString_thenReturnNonEmptyLineCount() {
    String multilineStr = "This is\n \n a multiline\n string.";

    long lineCount = multilineStr.lines()
      .filter(String::isBlank)
      .count();

    is(lineCount).equals(3L);
}

8. 总结

Java 11 和 Java 12 为 String 类新增了多个实用方法,包括:

方法名 用途说明
indent() 调整字符串每行的缩进
transform() 对字符串应用函数转换
repeat() 重复拼接字符串
strip() 去除首尾空白(支持 Unicode)
isBlank() 判断是否为空或空白字符串
lines() 将字符串按行转为 Stream

这些方法让字符串处理更加简洁高效,是日常开发中非常值得掌握的技巧。


示例代码已整理至 GitHub,欢迎查看:GitHub 链接(模拟地址)


原始标题:Java String API – New Methods | Baeldung