C# 截取中英文混合字符串分行显示宽度相同

来源:互联网 发布:网络歌曲软绵绵 编辑:程序博客网 时间:2024/05/21 09:22

 /// <summary>
/// 截取指定长度(宽度一样)字符串,区分中英文
/// </summary>
/// <param name="str">要截取的字符串</param>
/// <param name="length">截取长度</param>
/// <returns>截取后的字符串</returns>
public static string CutStr(string str, int length)
{
if (length < 1) return str;

if (System.Text.Encoding.Default.GetByteCount(str) <= length)
{
return str;
}
else
{
byte[] txtBytes = System.Text.Encoding.Default.GetBytes(str);
byte[] newBytes = new byte[length - 4];

for (int i = 0; i < length - 4; i++)
{
newBytes[i] = txtBytes[i];
}

return System.Text.Encoding.Default.GetString(newBytes) + "... ";
}
}
0 0