我想实现一个功能,如果一个词太长而不能出现在一行中,则插入一个分词标记。
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("​");//<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/