/// <summary>
/// 取指定长度的Unicode字符,如:
/// str="I'm 张三"
/// startIndex=0
/// len=3
/// 则返回"I'm 张"
/// </summary>
/// <param name="str"></param>
/// <param name="startIndex">开始位置</param>
/// <param name="len">表示要取的与该数汉字相等的字符的长度</param>
/// <returns></returns>
public static string GetSubStr(string str, int startIndex, int len)
{
return GetSubStr(str, startIndex, len, "");
}
/// <summary>
/// 取指定长度的Unicode字符,如:
/// str="I'm 张三"
/// startIndex=0
/// len=3
/// 则返回"I'm 张"
/// </summary>
/// <param name="str"></param>
/// <param name="startIndex">开始位置</param>
/// <param name="len">表示要取的与该数汉字相等的字符的长度</param>
/// <returns></returns>
public static string GetSubStr(string str, int startIndex, int len, string AppendStr)
{
byte[] buffer = System.Text.Encoding.Unicode.GetBytes(str);
double len_Temp = 0;
System.Text.StringBuilder SB = new System.Text.StringBuilder();
for (int i = startIndex * 2; i < buffer.Length - 1; i = i + 2)
{
if (len_Temp >= len)
break;
if (buffer[i + 1] == 0)
{
len_Temp += 0.5;
}
else
len_Temp++;
SB.Append(System.Text.Encoding.Unicode.GetChars(buffer, i, 2));
}
if (AppendStr != null && AppendStr != "" && SB.ToString().Length < str.Length)
SB.Append(AppendStr);
return SB.ToString();
}
/// <summary>
/// 取字符串长度
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public int GetLength(string str)
{
byte[] buffer = System.Text.Encoding.Unicode.GetBytes(str);
double len_Temp = 0;
for (int i = 0; i < buffer.Length - 1; i = i + 2)
{
if (buffer[i + 1] == 0) //Unicode编码每个字符占两个byte,英文字符高位为0
len_Temp += 0.5;
else
len_Temp++;
}
string[] arr1 = len_Temp.ToString("0.00").Split('.');
int ReturnValue = Convert.ToInt32(arr1[0]);
if ((len_Temp % ReturnValue) != 0)
ReturnValue++;
return ReturnValue;
}