You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何统计含U+200B的字符串中可见字符的数量?

如何统计含零宽空格字符串中的可见字符数量?

给定包含U+200B(零宽空格)的字符串:

string x = "​​​h​​​el​​​lo​​​";

直接调用x.Count()会将不可见的零宽空格计入总数,得到结果17,但实际可见字符仅5个。以下是几种获取可见字符数量的方法:

  • 方法1:直接排除指定的零宽空格字符
    通过LINQ筛选出不是U+200B的字符,再统计数量:

    using System.Linq;
    
    int visibleCount = x.Count(c => c != '\u200B');
    Console.WriteLine(visibleCount); // 输出5
    
  • 方法2:清理字符串后统计长度
    先移除所有U+200B字符,再获取清理后字符串的长度:

    string cleanedStr = x.Replace("\u200B", string.Empty);
    int visibleCount = cleanedStr.Length;
    Console.WriteLine(visibleCount); // 输出5
    
  • 方法3:排除所有格式类不可见字符
    如果需要处理除U+200B外的其他格式类不可见字符,可以通过UnicodeCategory判断并排除:

    using System.Linq;
    using System.Globalization;
    
    int visibleCount = x.Count(c => CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.Format);
    Console.WriteLine(visibleCount); // 输出5
    

    注意:这种方法会排除所有Unicode格式类字符,若字符串中存在需要保留的格式字符(如特定连字符号),不建议使用。

内容的提问来源于stack exchange,提问作者MaKeSter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 15:53:21