我这里有段代码,这里可以限制文字最大长度超出的时候用...替代。
但是无法针对英文字符作为半个文字大小设置长度。
有没有办法做到英文算半个长度,中文算一个?这样的函数该如何写?public static string GetShortText(object TextSrc, int MaxLenth)
{
string Text = TextSrc.ToString();
if (Text.Length > MaxLenth)
return Text.Substring(0, MaxLenth) + "...";
else
return Text;
}
但是无法针对英文字符作为半个文字大小设置长度。
有没有办法做到英文算半个长度,中文算一个?这样的函数该如何写?public static string GetShortText(object TextSrc, int MaxLenth)
{
string Text = TextSrc.ToString();
if (Text.Length > MaxLenth)
return Text.Substring(0, MaxLenth) + "...";
else
return Text;
}
实际长度
protected string CutStr(string str,int len)
{
byte[] b = System.Text.Encoding.Default.GetBytes(str);
if(b.Length>len)
{
string result = "";
for(int i=0;i<str.Length;i++)
{
byte[] tempByte=System.Text.Encoding.Default.GetBytes(result);
if(tempByte.Length<len)
{
result += str.Substring(i,1);
}
else
{
break;
}
}
return result + "...";
}
else
{
return str;
}
}