前两天在开发中遇到了截取字符串的问题,使用C#中的SubString时,不论汉字还是字母,全角还是半角,都当做一个字符处理,无法适应页中显示的要求,于是自己写了个StringSub,截取时全角字符计为两个长度,而半角字符计为一个,未经严格测试
,代码如下:
/// <summary>
/// 对指定字符串取指定长度,考虑了全角半角的问题
/// </summary>
/// <param name="str"></param>
/// <param name="len"></param>
/// <returns></returns>
public static string StringSub(string str, int len)
{
string temp = "";
System.Text.ASCIIEncoding n = new System.Text.ASCIIEncoding();
byte[] b = n.GetBytes(str);
int i = 0;
int j = 0;
while (i < len && j < b.Length)
{
temp += str.Substring(0, 1);
str = str.Substring(1);
if (b[j] >= 63)
i = i + 2;
else
i++;
j++;
}
return temp;
}
,代码如下:/// <summary>
/// 对指定字符串取指定长度,考虑了全角半角的问题
/// </summary>
/// <param name="str"></param>
/// <param name="len"></param>
/// <returns></returns>
public static string StringSub(string str, int len)
{
string temp = "";
System.Text.ASCIIEncoding n = new System.Text.ASCIIEncoding();
byte[] b = n.GetBytes(str);
int i = 0;
int j = 0;
while (i < len && j < b.Length)
{
temp += str.Substring(0, 1);
str = str.Substring(1);
if (b[j] >= 63)
i = i + 2;
else
i++;
j++;
}
return temp;
}
浙公网安备 33010602011771号