这是经过加特殊处理后得到允许较为满意的代码,发布分享。南無阿弥陀佛!
protected string CutString(string str, int length)//文字省略
{
int Zj = 0, Hc = 0, YingWen = 0, ZongWen = 0;
string NewString = "", Tstr = ""; string[] XinXi = new string[2];
XinXi = str.Split(new char[3] { ' ', '/r', '/n' });//去掉换行、回车、空格
for (int Qd = 0; Qd < XinXi.Length; Qd++)//重新组合
{ Tstr += XinXi[Qd].ToString(); }
int i = System.Text.Encoding.Default.GetBytes(Tstr).Length;//混合长度
int j = Tstr.Length;//本身长度
if (Tstr != "")
{
if (i / j == 2 || i == j || j < length) { Hc = length; }//纯中文、纯英文、本身长度小于
else//混合字符串
{
for (int Hh = 0; Hh < Tstr.Length; Hh++)
{
int Zz = System.Text.Encoding.Default.GetBytes(Tstr.Substring(Hh, 1)).Length;
if (Zz == 2) { length = length - 1; }
if (Zz == 1) { Zj++; if (Zj % 2 == 0) { length = length - 1; } }//逢二减一
if (length == 0) //特殊处理
{
ZongWen = System.Text.Encoding.Default.GetBytes(Tstr.Substring(Hh - 1, 1)).Length;
YingWen = System.Text.Encoding.Default.GetBytes(Tstr.Substring(Hh + 1, 1)).Length;
if (Zj % 2 == 0 && Zz == 2) { Hc = Hh + 1; break; }//逢偶补一
else if (Zz == 1 && YingWen == 1 && ZongWen == 1) { Hc = Hh + 2; break; }//前中后都是英文的特殊处理
else { Hc = Hh; break; }
}
}
}
if (j > Hc) { NewString = Tstr.Substring(0, Hc) + "..."; } else { NewString = Tstr; }
}
return NewString;
}
这两天刚写出来的控制页面显示文字长度的,在论坛中找到的运行都不是很满意,自己写了这个运行还比较满意,发表分享
protected string CutString(string str, int length)//文字省略
{
int Zj = 0, Hc = 0, Qs = 0; bool Jz = false;
string NewString = "", Tstr = ""; string[] XinXi = new string[2];
XinXi = str.Split(new char[3] { ' ', '/r', '/n' });//去掉换行、回车、空格
for (int Qd = 0; Qd < XinXi.Length; Qd++)//重新组合
{ Tstr += XinXi[Qd].ToString(); }
int i = System.Text.Encoding.Default.GetBytes(Tstr).Length;//混合长度
int j = Tstr.Length;//本身长度
if (Tstr != "")
{
if (i / j == 2 || i == j || j < length) { Hc = length; }//纯中文、纯英文、本身长度小于
else//混合字符串
{
for (int Hh = 0; Hh < Tstr.Length; Hh++)
{
int Zz = System.Text.Encoding.Default.GetBytes(Tstr.Substring(Hh, 1)).Length;
if (length == 1)
{
Qs = System.Text.Encoding.Default.GetBytes(Tstr.Substring(Hh - 1, 1)).Length;
if (Qs == 1 && Zz == 1) { Jz = true; } //前后都是英文的特殊处理
}
if (Zz == 2) { length = length - 1; }
if (Zz == 1) { Zj++; if (Zj % 2 == 0) { length = length - 1; } }//逢二减一
if (length == 0) //特殊处理
{
if (Zj % 2 == 0 && Zz == 2) { Hc = Hh + 1; break; } else { Hc = Hh; break; }//逢偶补一
}
}
}
if (j > Hc) { NewString = Tstr.Substring(0, Hc) + "..."; } else { NewString = Tstr; }
}
return NewString;
}
以下简易型:
protected string CutString(object str, object length)
{
string newString = "";int lengthi=Convert.ToByte(length.ToString());
if (str.ToString() != "")
{
if (str.ToString().Length > lengthi)
{
newString = str.ToString().Substring(0, lengthi) + "...";
}
else
{
newString = str.ToString().;
}
}
return newString;
}
有这么一个方法!
前台:
我用TextBox 调用
<asp:TextBox ID="TextBox1" runat="server" Text=' <%# CutString(DataBinder.Eval("NewTitle"),"5") %>'> </asp:TextBox>