static public int StringLength(string str)
{
byte[] strbytes;
int tmpcnt = 0;
for (int i = 0 ; i < str.Length ; i++)
{
strbytes = Encoding.UTF8.GetBytes(str.Substring(i,1));
if (strbytes.Length == 3)
{
tmpcnt += 2;
}
else
{
tmpcnt += 1;
}
}
return tmpcnt;
}
{
byte[] strbytes;
int tmpcnt = 0;
for (int i = 0 ; i < str.Length ; i++)
{
strbytes = Encoding.UTF8.GetBytes(str.Substring(i,1));
if (strbytes.Length == 3)
{
tmpcnt += 2;
}
else
{
tmpcnt += 1;
}
}
return tmpcnt;
}
本文介绍了一个使用C#编写的静态公共方法StringLength,该方法用于计算字符串的实际显示长度,特别适用于包含多种字符(包括中文和特殊符号)的情况。通过对每个字符进行UTF-8编码并检查其字节数来确定其实际占用的空间。
718

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



