c# - 如何在不拆分 html 编码的特殊字符内的情况下按长度启用分词功能

标签 c# string

我想实现一个功能,如果一个词太长而不能出现在一行中,则插入一个分词标记。

    protected string InstertWBRTags(string text, int interval)
{
    if (String.IsNullOrEmpty(text) || interval < 1 || text.Length < interval)
    {
        return text;
    }
    int pS = 0, pE = 0, tLength = text.Length;
    StringBuilder sb = new StringBuilder(tLength * 2);

    while (pS < tLength)
    {
        pE = pS + interval;
        if (pE > tLength)
            sb.Append(text.Substring(pS));
        else
        {
            sb.Append(text.Substring(pS, pE - pS));
            sb.Append("&#8203;");//<wbr> not supported by IE 8
        }
        pS = pE;
    }
    return sb.ToString();
}

问题是:如果文本包含 html 编码的特殊字符,我该怎么办? 我该怎么做才能防止在 ß 中插入 TAG? 我能做些什么来计算真正的字符串长度(出现在浏览器中)? 像 ♡♥♡♥ 这样的字符串在浏览器中只包含 2 个字符(红心),但它的长度是 14。

最佳答案

一种解决方案是将实体解码为它们所代表的 Unicode 字符并与之一起使用。这样做use System.Net.WebUtility.HtmlDecode() if you're in .NET 4 or System.Web.HttpUtility.HtmlDecode() otherwise .

但请注意,并非所有 Unicode 字符都适合一个 char

关于c# - 如何在不拆分 html 编码的特殊字符内的情况下按长度启用分词功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3300058/

相关文章:

c# - 使用 web api HttpResponseMessage 输出图像

ios - 将千位分隔符 "˙"添加到 float

Java 字符串 intToStr = ""+ 5;为什么我不能这样做?

java - 仅替换字符串中第二次出现的位置

c# - 如何使用用户凭据访问 Azure Key Vault?

c# - 获取所有连接的智能卡的列表

c# - 无法使用 'where' 类型约束转换泛型参数?

C# 使用附加参数附加事件处理

c - C 中字符串中的数字相乘

java - 检查字符串数组是否包含值