/// <summary>
/// 根据字节数截取字符串(区分汉字、数字、字母)
/// </summary>
/// <param name="str"></param>
/// <param name="n"></param>
/// <returns></returns>
public string stringFormat(string str, int n)
{
///
///格式化字符串长度,区分汉字跟字母。汉字2个字节,字母数字一个字节
///
string temp = string.Empty;
if (System.Text.Encoding.Default.GetByteCount(str) <= n * 2 - 2)//如果长度比需要的长度n小,返回原字符串
{
return str;
}
else
{
int t = 0;
char[] q = str.ToCharArray();
for (int i = 0; i < q.Length; i++)
{
//if ((int)q[i] >= 0x4E00 && (int)q[i] <= 0x9FA5)//是否汉字
if (Convert.ToInt32(q[i]) > 255)//是否汉字
{
temp += q[i];
t += 2;
}
else
{
temp += q[i];
t += 1;
}
if (t >= n * 2)
{
break;
}
}
if (Encoding.GetEncoding("GBK").GetBytes(temp).Length > n * 2)
{
temp = temp.Remove(temp.Length - 1, 1);
}
return temp;
}
}
来源:https://www.cnblogs.com/lfg123/p/9700315.html