public class SubStrHelper
{
/// <summary>
/// 截取字符串长度,中文二字节
/// </summary>
/// <param name="str"></param>
/// <param name="length">字节长度</param>
/// <returns></returns>
public static string GetSubString(string str, int byteLength, string moreTag = "...")
{
string temp = str;
int j = 0;
int k = 0;
for (int i = 0; i < temp.Length; i++)
{
// if (Regex.IsMatch(temp.Substring(i, 1), @"[\u4e00-\u9fa5]+")) //匹配中文
if (Regex.IsMatch(temp.Substring(i, 1), @"[^\x00-\xff]+")) //匹配双字节字符(包括中文)
{
j += 2;
}
else
{
j += 1;
}
if (j <= byteLength)
{
k += 1;
}
if (j > byteLength)
{
return string.Format("{0}{1}", temp.Substring(0, k), moreTag);
}
}
return temp;
}
}
时间: 2024-10-29 19:11:51