你说的字符,应该是一个英文数字算一个字符,一个汉字算2个字符的。如果这样的花,用Substring这样就不行了。 给你个正则处理方法: using System.Text.RegularExpressions; public static string getSubStr(string str, int length) { int j = 0; int k = 0; int ll=str.Length; for (int i = 0; i < ll; i++) { if (Regex.IsMatch(str.Substring(i, 1), @"[\u4e00-\u9fa5]+")) { j += 2; } else { j += 1; } if (j <= length) { k += 1; } if (j >= length) { return str.Substring(0, k); } } return str; }这样就取到实际的字符数了,而不是数量。
{
if(str.Length>10)
{
str=str.Substring(0, 10);
}
return str;
}前台绑定:
<%# Cutstr(Eval("content").ToString()) %>
<ItemTemplate>
<asp:Label ID="tle1" runat="server" Text='<%#Eval("title")%>'></asp:Label> <br /><br />
</ItemTemplate>
</asp:Repeater>
后台:
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
string text = ((Label)e.Item.FindControl("tle1")).Text.Trim();
if (text.Length > 10)
{
text = text.Substring(0, 10);
((Label)e.Item.FindControl("tle1")).Text = text ;
}
}
如果直接截,长度不够10的情况下,会出现错误的,如上解决方案:如下<%#Eval("ProductName").ToString().Length > 10 ? Eval("ProductName").ToString().Substring(0, 10) : Eval("ProductName")%>
用sql里的substring(title,0,10) 重新启字段名
绑定这个字段多简单
string s= "";
byte[] b= Encoding.UTF8.GetBytes(s);
byte[] buffer = new byte[12];
Buffer.BlockCopy(b, 0, buffer, 0, buffer.Length);
真够疯狂的。最好的办法是写个辅助函数,像#1楼那样,不过如果稍稍改一下,就更好用了。Eval 返回的是object 类型,实际类型有可能是 DbNull 或其他的非 string 类型,这些在绑定语法里处理会让人眼花
public string Cutstr(object obj)
{
string str = obj as string;
if (str == null)
{
return "";
} if(str.Length>10)
{
str=str.Substring(0, 10) + "...";
}
return str;
}
给你个正则处理方法:
using System.Text.RegularExpressions; public static string getSubStr(string str, int length)
{
int j = 0;
int k = 0;
int ll=str.Length;
for (int i = 0; i < ll; i++)
{
if (Regex.IsMatch(str.Substring(i, 1), @"[\u4e00-\u9fa5]+"))
{
j += 2;
}
else
{
j += 1;
}
if (j <= length)
{
k += 1;
}
if (j >= length)
{
return str.Substring(0, k);
}
}
return str;
}这样就取到实际的字符数了,而不是数量。