获取指定字节长度的字符串

public static string GetStringByBytes(string str, int len)
{
if (str == null)
return string.Empty;

int j = 0, k = 0;
ASCIIEncoding encoding = new ASCIIEncoding();
for (int i = 0; i < str.Length; i++)
{
byte[] bytes = Encoding.Default.GetBytes(str.Substring(i, 1));
if (bytes.Length == 2)//不是英文
{
j = j + 2;
}
else
j++;

if (j <= len)
k += 1;

else if (j >= len)
return str.Substring(0, k - 2) + "...";
}
return str;
}

原文地址:https://www.cnblogs.com/pengzhihua/p/4825953.html