/// <summary>
/// 获取制定字符串的前L位字符,注:半角字符只算半个字符
/// </summary>
/// <param name="s">制定的字符串</param>
/// <param name="l">长度</param>
/// <param name="adddot">超出长度时追加的字符</param>
/// <returns></returns>
public static string SubGBString(string s, int l, string adddot)
{
string c = @"abcdefghijklmnopqrstuvwzxyABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()-=_+[];',./{}:\<>? \|";
string cc = "";
int p = 0;
for (int i = 0; i < s.Length; i++)
{
cc = s.Substring(i, 1);
if (c.IndexOf(cc) >= 0)
p++;
else
p = p + 2;
if ((p - 1) / 2 >= l)
{
string reval=s.Substring(0, i);
reval = reval + adddot;
return reval;
}
}
return s;
}
/// <summary>
/// 获取制定字符串的前L位字符,注:全角字符算2个字符
/// </summary>
/// <param name="s">制定的字符串</param>
/// <param name="l">长度</param>
/// <param name="r">长度不够时填充的字符</param>
/// <returns></returns>
public static string SubByteString(string s, int l, string r)
{
string c = @"abcdefghijklmnopqrstuvwzxyABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()-=_+[];',./{}:\<>? \|";
string cc = "";
int p = 0;
for (int i = 0; i < s.Length; i++)
{
cc = s.Substring(i, 1);
if (c.IndexOf(cc) >= 0)
p++;
else
p = p + 2;
if (p + 1 > l)
return s.Substring(0, i) + "..";
}
if (r != "")
{
string str = r;
for (int i = 0; i <= l; i++)
{
str += r;
}
return s + " " + str.Substring(0, l - p);
}
else
{
return s;
}
}
/// <summary>
/// 截取字符串(按全角长度,一个全角等于两个半角)
/// </summary>
/// <param name="str">字符串</param>
/// <param name="length">截取长度(全角)</param>
/// <returns></returns>
public String InterceptString(String str, Int32 length)
{
if (str.Length > length)
{
string newStr = "";
length = length * 2;
foreach (char ch in str)
{
if (ch >= 32 && ch <= 126)//半角
{
length--;
}
else// 全角
{
length = length - 2;
}
if (length < 0) break;
newStr += ch;
}
str = newStr;
}
return str;
}
转载请注明出处:http://blog.csdn.net/dasihg/article/details/6781391