〇×〇站

个人博客,佛系更新

Java以字素单位获取字符串长度

  • Pluto
  • 2024-04-10 16:19:03
  • 11
  • 转自https://stackoverflow.com/questions/40878804/how-to-count-grapheme-clusters-or-perceived-emoji-characters-in-java

    1. 引入 ICU library

    <dependency>
        <groupId>com.ibm.icu</groupId>
        <artifactId>icu4j</artifactId>
        <version>74.2</version>
    </dependency>
    

    2. 使用

    public static int getLength(String emoji) {
        BreakIterator it = BreakIterator.getCharacterInstance();
        it.setText(emoji);
        int emojiCount = 0;
        while (it.next() != BreakIterator.DONE) {
            emojiCount++;
        }
        return emojiCount;
    }
    
    分类:
  • 代码
  • 标签:
  • java