您的位置:首页 > 编程语言 > C#

c#完美截断字符串代码(中文+非中文)

2018-10-12 14:09 447 查看

public static string Truncation(this HtmlHelper htmlHelper, string str, int len)
{
if (str == null || str.Length == 0 || len <= 0)
{
return string.Empty;
}
int l = str.Length;
#region 计算长度
int clen = 0;
while (clen < len && clen < l)
{
//每遇到一个中文,则将目标长度减一。
if ((int)str[clen] > 128) { len--; }
clen++;
}
#endregion
if (clen < l)
{
return str.Substring(0, clen) + "...";
}
else
{
return str;
}
}

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: