public static string GetString(this HtmlHelper htmlHelper, string s, int l, string endStr)
{
string temp = s.Substring(0, (s.Length < l + 1) ? s.Length : l + 1);
byte[] encodedBytes = Encoding.ASCII.GetBytes(temp);
string outputStr = string.Empty;
int count = 0;
for (int i = 0; i < temp.Length; i++)
{
if (encodedBytes[i] == 63)
{
count += 2;
}
else
{
count += 1;
}
if (count <= l - endStr.Length)
{
outputStr += temp.Substring(i, 1);
}
else if (count > l)
{
break;
}
}
if (count <= l)
{
outputStr = temp;
endStr = string.Empty;
}
outputStr += endStr;
return outputStr;
}
{
string temp = s.Substring(0, (s.Length < l + 1) ? s.Length : l + 1);
byte[] encodedBytes = Encoding.ASCII.GetBytes(temp);
string outputStr = string.Empty;
int count = 0;
for (int i = 0; i < temp.Length; i++)
{
if (encodedBytes[i] == 63)
{
count += 2;
}
else
{
count += 1;
}
if (count <= l - endStr.Length)
{
outputStr += temp.Substring(i, 1);
}
else if (count > l)
{
break;
}
}
if (count <= l)
{
outputStr = temp;
endStr = string.Empty;
}
outputStr += endStr;
return outputStr;
}
本文介绍了一个实用的字符串处理方法,该方法可以基于字符编码大小动态调整字符串长度,并能够智能处理字符串截断后的编码完整性,确保显示效果。通过一个具体的C#实现案例,展示了如何在考虑字符编码的基础上截取字符串并添加结尾标识。
207

被折叠的 条评论
为什么被折叠?



