
截取字符串的前几字节(当遇到双字节时,则去掉最后一个字节)#region 截取字符串的前几字节(当遇到双字节时,则去掉最后一个字节)
/**//// <summary>
/// 截取字符串的前几个字节(当遇到双字节时 如:"中国" 截取3个字节,则变成 "中"
/// </summary>
/// <param name="s">字符串</param>
/// <param name="cutcount">字节</param>
/// <param name="outstr"></param>
/// <returns></returns>
public static string ToCutString(this string s, int cutcount, string outstr)
{
if (s == null) return "";
cutcount = System.Math.Abs(cutcount);
if (cutcount >= s.ToByteLenth())
{
return s;
}
else if (cutcount <= 0)
{
return "";
}
//============================
for (int i = 0; i < cutcount; i++)
{
if (s.Substring(i, 1).ToByteLenth() == 2)
{
cutcount -= 1;
}
}
return s.Substring(0, cutcount) + outstr;
}
#endregion

得到字符串的字节长度#region 得到字符串的字节长度
/**//// <summary>
/// 得到字符串的字节长度(null返回0)
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static int ToByteLenth(this string s)
{
if (s == null) return 0;
return Encoding.Default.GetBytes(s).Length;
}
#endregion

浙公网安备 33010602011771号