按指定字节长度截取字符串(每个汉字长度2字节)
按指定字节长度截取字符串(每个汉字长度2字节)
测试:
C# Code:
/// <summary>
/// 按指定字节长度截取字符串(每个汉字长度2字节)
/// </summary>
/// <param name="str">字符串</param>
/// <param name="byteLength">字节长度</param>
/// <returns></returns>
public static string CutStringByte(string str, int byteLength)
{
if (string.IsNullOrEmpty(str)) return "";
if (System.Text.Encoding.UTF8.GetByteCount(str) < byteLength) return str;
int i = 0;//字节数
int j = 0;//实际截取长度
foreach (char newChar in str)
{
if ((int)newChar > 127)
{
//汉字
i += 2;
}
else
{
i++;
}
if (i <= byteLength)
j++;
else
break;
}
str = str.Substring(0, j);
return str;
}
//来源:C/S框架网 | www.csframework.com | QQ:23404761
/// <summary>
/// 按指定字节长度截取字符串(每个汉字长度2字节)
/// </summary>
/// <param name="str">字符串</param>
/// <param name="byteLength">字节长度</param>
/// <returns></returns>
public static string CutStringByte(string str, int byteLength)
{
if (string.IsNullOrEmpty(str)) return "";
if (System.Text.Encoding.UTF8.GetByteCount(str) < byteLength) return str;
int i = 0;//字节数
int j = 0;//实际截取长度
foreach (char newChar in str)
{
if ((int)newChar > 127)
{
//汉字
i += 2;
}
else
{
i++;
}
if (i <= byteLength)
j++;
else
break;
}
str = str.Substring(0, j);
return str;
}
//来源:C/S框架网 | www.csframework.com | QQ:23404761
测试:
C# Code:
//返回:按指定(字
string str = CutStringByte("按指定(字节)长度截取字符串", 10);
//返回:Applicatio
string str = CutStringByte("按指定(字节)长度截取字符串", 10);
//返回:Applicatio
string str1 = CutStringByte("Application.SetCompatibleTextRenderingDefault(false);", 10);
//来源:C/S框架网 | www.csframework.com | QQ:23404761
//来源:C/S框架网 | www.csframework.com | QQ:23404761
版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
NewDoc C/S框架网