/// <summary>
/// 格式化字符串长度,超出部分显示省略号,区分汉字跟字母。汉字2个字节,字母数字一个字节
/// </summary>
/// <param name="str">字符串</param>
/// <param name="n">截取长度</param>
/// <returns></returns>
public static string Substringforlength(string str, int n)
{
string temp = string.Empty;
if (System.Text.Encoding.Default.GetByteCount(str) <= n)//如果长度比需要的长度n小,返回原字符串
{
return str;
}
else
{
int t = 0;
char[] q = str.ToCharArray();
for (int i = 0; i < q.Length; i++)
{
if ((int)q[i] >= 0x4E00 && (int)q[i] <= 0x9FA5)//是否汉字
{
temp += q[i];
t += 2;
}
else
{
temp += q[i];
t += 1;
}
if (t >= n)
{
break;
}
}
return temp;
}
}
/// <summary>
/// 字符串长度换行/n 返回StringBuilder
/// </summary>
/// <param name="str">str</param>
/// <param name="length">限制字节长度</param>
/// <returns></returns>
public static string returnstr(string str, int length)
{
StringBuilder sb = new StringBuilder();
string str1="", str2 = "";
int len = getLen(str);
int num = len / length+ (len % length == 0 ? 0 :1);
int strlength =0;
for (int i = 0; i < num; i++)
{
if (System.Text.Encoding.Default.GetByteCount(str) > length)
{
str1 = Substringforlength(str, length);
sb.Append(str1 + "/n");
strlength = str1.Length;
str2 = str.Substring(strlength);
str = str2;
}
else {
sb.Append(str + "/n");
str = "";
}
}
return sb.ToString();
}