截取字符串,区分中英字母长度
/// <summary>
/// 截取字符串
/// </summary>
/// <param name="str"></param>
/// <param name="maxByteCount"></param>
/// <returns></returns>
private static string TrancateString(string str, int maxByteCount)
{
if (string.IsNullOrWhiteSpace(str))
{
return "";
}
var count = Encoding.Default.GetByteCount(str);
if (count > maxByteCount)
{
var result = "";
var charnum = 0;
var array = str.ToCharArray();
for (int i = 0; i < array.Length; i++)
{
var one = str[i];
if (one >= 0x4e00 && one <= 0x9fa5)
{
charnum += 2;
}
else
charnum += 1;
if (maxByteCount >= charnum)
result += one;
else
{
return result;
}
}
return result;
}
else
{
return str;
}
}