Skip to content

String 新方法

JDK 11 为 String 类添加了 5 个实用方法。这些方法在其他语言里早就有了,Java 终于补上了。

快速概览

java
"  hello  ".isBlank();        // true - 判断空白
"hello\nworld".lines();         // Stream<String> - 按行分割
"  hello  ".strip();            // "hello" - 去空白(Unicode)
"hello".repeat(3);              // "hellohellohello" - 重复
"".isEmpty();                  // true - 判断空字符串

详细说明

isBlank() — 判断是否空白

java
public class IsBlankDemo {

    public static void main(String[] args) {
        // 空白字符:空格、Tab、换行等
        System.out.println("".isBlank());              // true
        System.out.println("   ".isBlank());           // true(空格)
        System.out.println("\t".isBlank());            // true(Tab)
        System.out.println("\n".isBlank());            // true(换行)
        System.out.println("\t\n  ".isBlank());       // true(混合)
        System.out.println("hello".isBlank());         // false
        System.out.println(" hello ".isBlank());      // false(中间有空格)
        
        // 实际应用:表单验证
        String username = "   ";
        if (username.isBlank()) {
            System.out.println("用户名不能为空或仅包含空白字符");
        }
    }
}

注意" ".isBlank() 返回 true,但 " ".isEmpty() 返回 false。 一个是判断"是否空白",一个是判断"是否为空串(长度为 0)"。

lines() — 按行分割

java
public class LinesDemo {

    public static void main(String[] args) {
        String text = "第一行\n第二行\n第三行";
        
        // 返回 Stream<String>
        text.lines().forEach(System.out::println);
        
        // 输出:
        // 第一行
        // 第二行
        // 第三行
        
        // 支持各种换行符
        String multiline = "a\nb\rc\rd";  // \n, \r, \r\n
        long count = multiline.lines().count();
        System.out.println("行数: " + count);  // 4
        
        // 实际应用:处理日志
        String logs = """
            INFO: 应用启动
            DEBUG: 加载配置
            ERROR: 连接失败
            INFO: 重试中
            """;
        
        long errorCount = logs.lines()
            .filter(line -> line.contains("ERROR"))
            .count();
        System.out.println("错误日志数: " + errorCount);
    }
}

注意lines() 使用正则 \R 匹配换行符,能正确处理 \n\r\r\n

strip() — 去空白(Unicode)

java
public class StripDemo {

    public static void main(String[] args) {
        String s = "  hello  ";
        
        System.out.println("strip():  '" + s.strip() + "'");   // 'hello'
        System.out.println("trim():   '" + s.trim() + "'");    // 'hello'
        
        // 区别在于 Unicode 空白字符
        // trim() 只处理 ASCII 空白:\u0020 及之前
        // strip() 处理所有 Unicode 空白
        String unicode = "\u2003hello\u2003";  // 全角空格
        System.out.println("trim:   '" + unicode.trim() + "'");   // '    hello    '
        System.out.println("strip:  '" + unicode.strip() + "'");   // 'hello'
        
        // stripLeading() / stripTrailing()
        System.out.println("stripLeading:   '" + "  hello  ".stripLeading() + "'");   // 'hello  '
        System.out.println("stripTrailing:  '" + "  hello  ".stripTrailing() + "'");  // '  hello'
    }
}

Unicode 空白字符举例:

字符Unicodetrim()strip()
普通空格U+0020
全角空格U+3000
不间断空格U+00A0
制表符U+0009
中文空格U+3000

repeat() — 重复字符串

java
public class RepeatDemo {

    public static void main(String[] args) {
        // 基本用法
        System.out.println("na ".repeat(3) + "Batman!");
        // 输出: na na na Batman!
        
        System.out.println("-".repeat(20));
        // 输出: --------------------
        
        System.out.println("*".repeat(5));
        // 输出: *****
        
        // 边界情况
        System.out.println("abc".repeat(0));  // ""(空串)
        System.out.println("abc".repeat(1));  // "abc"
        
        // 实际应用:文本装饰
        String title = " 报表 ";
        int width = 30;
        String border = "*".repeat(width);
        System.out.println(border);
        System.out.println(title.center(width - 2).indent(1));
        System.out.println(border);
        
        // 生成 SQL VALUES
        String values = List.of("a", "b", "c").stream()
            .map(s -> "'" + s + "'")
            .collect(Collectors.joining(", "));
        System.out.println("INSERT INTO t VALUES (" + values + ")");
        // INSERT INTO t VALUES ('a', 'b', 'c')
    }
}

与旧方法的对比

方法JDK 版本空白字符返回类型
trim()1.0ASCII 空白String
strip()11Unicode 空白String
isEmpty()1.6boolean
isBlank()11Unicode 空白boolean

trim vs strip 实战对比

java
public class TrimVsStrip {

    public static void main(String[] args) {
        // 场景一:用户输入
        String input = "   张三   ";
        // 前端传来或表单输入,可能包含各种空白
        System.out.println("strip: '" + input.strip() + "'");  // '张三'
        
        // 场景二:CSV 解析
        String csvLine = "name, age, city";
        String[] fields = csvLine.split(",");
        // 每个字段可能带空白
        for (String field : fields) {
            System.out.println("'" + field.strip() + "'");
        }
        // 输出: 'name', 'age', 'city'
        
        // 场景三:读取配置文件
        String configLine = "\t\tkey=value\t\n";
        String key = configLine.split("=")[0].strip();
        String value = configLine.split("=")[1].strip();
        System.out.println(key + " = " + value);  // key = value
    }
}

实用场景

场景一:处理多行文本

java
String markdown = """
    # 标题
    ## 子标题
    
    正文内容。
    - 列表项 1
    - 列表项 2
    """;

// 提取非空行
List<String> lines = markdown.lines()
    .filter(line -> !line.isBlank())
    .toList();

// 统计字数
long wordCount = markdown.lines()
    .flatMap(line -> Arrays.stream(line.split("\\s+")))
    .filter(word -> !word.isEmpty())
    .count();

场景二:文本对齐

java
// 使用 repeat 实现文本框
String text = "Hello";
int width = 20;

String box = """
    ┌%s┐
    │%s│
    └%s┘
    """.formatted(
        "-".repeat(width),
        text.center(width),
        "-".repeat(width)
    );

System.out.println(box);

场景三:构建重复结构

java
// 生成表格
String[] headers = {"Name", "Age", "City"};
String[] values = {"Alice", "25", "Beijing"};

String separator = "+" + Arrays.stream(headers)
    .map(h -> "-".repeat(h.length() + 2))
    .collect(Collectors.joining("+")) + "+";

String headerRow = "|" + Arrays.stream(headers)
    .map(h -> " " + h + " ")
    .collect(Collectors.joining("|")) + "|";

System.out.println(separator);
System.out.println(headerRow);
System.out.println(separator);

小结

JDK 11 的 String 新方法解决了实际痛点:

方法场景
isBlank()验证用户输入
lines()处理日志、多行文本
strip()去空白(兼容 Unicode)
stripLeading()只去前导空白
stripTrailing()只去尾部空白
repeat()生成重复结构
java
// 推荐用 strip() 代替 trim()
String clean = input.strip();  // ✅
String clean = input.trim();     // ❌ 有 Unicode 空白处理不了

基于 VitePress 构建