#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
本文介绍了一种截取字符串的方法,该方法能够处理包含双字节字符的情况,并提供了一个获取字符串字节长度的实用函数。适用于需要对字符串进行特定字节数量截断的应用场景。


257





