截取中英混合字符串指定长度(转)
截取中英混合字符串指定长度(转)
/// <summary>
/// 截取中英混合字符串指定长度
/// </summary>
/// <param name="str">中英混合的字符串</param>
/// <param name="length">长度</param>
/// <returns></returns>
public static string GetStringByLength(string str, int length)
{
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]+"))
{
j += 2;
}
else
{
j += 1;
}
if (j <= length)
{
k += 1;
}
if (j >= length)
{
return temp.Substring(0, k);
}
}
return temp;
}