【问题标题】:How to get the substring that contains the first N unicode characters in Java如何获取包含Java中前N个unicode字符的子字符串
【发布时间】:2014-02-19 05:48:19
【问题描述】:

Java 中的 String 数据类型通过 codePointCount 让我们知道字符串中有多少个 unicode 字符;以及如何通过 codePointAt 获取第 n 个 unicode char。我想知道是否有 API 可以获取包含 Java 中前 N 个 unicode 字符的子字符串。

谢谢,

【问题讨论】:

    标签: java unicode substring


    【解决方案1】:

    查看java源代码:java.util.stream.Collectors#joining()

    .codePoints().limit(255) // limit as you need
        .collect(StringBuilder::new, StringBuilder::appendCodePoint, null)
    

    【讨论】:

    • 请为您的代码添加一些解释以帮助其他人
    【解决方案2】:

    没有一种方法可以一次性完成,但offsetByCodePoints() 会帮助您做到这一点。

    static String substring(String str, int idx, int len) {
      return str.substring(idx, str.offsetByCodePoints(idx, len));
    }
    

    【讨论】:

    • 不是必须是substring(str.offsetByCodePoints(0, idx), str.offsetByCodePoints(0, idx+len))吗?
    • 这取决于idx参数是字符偏移量还是码点偏移量。字符串方法一般采用字符偏移量,而那些使用码点的方法旨在将码点偏移量转换为字符偏移量。
    猜你喜欢
    • 2018-02-19
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    • 1970-01-01
    • 2020-08-26
    • 2021-02-11
    相关资源
    最近更新 更多