302班

java突击队
posts - 151, comments - 74, trackbacks - 0, articles - 14
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

字符串的任意截取技巧

Posted on 2007-04-10 14:17 停留的风 阅读(342) 评论(0)  编辑  收藏 所属分类: .NET技巧特辑

方法1:

/// <summary>
/// 按字符串实际长度截取定长字符窜
/// </summary>
/// <param name="str">原字符串</param>
/// <param name="length">要截取的长度</param>
/// <returns>string型字符串</returns>
public static string GetString(string str, int length)
{
int i = 0, j = 0;
foreach(char chr in str)
{
if((int)chr > 127)
{
i += 2;
}
else
{
i ++;
}
if (i > length)
{
str = str.Substring(0, j) + "...";
break;
}
j ++;
}
return str;

}

方法2:
再.cs文件里写一个函数
public  string CutString(string str,int length)
              {
                     int i = 0, j = 0;
                     foreach(char chr in str)
                     {
                            if((int)chr > 127)
                                   {
                                          i += 2;
                                   }
                            else
                                   {
                                          i ++;
                                   }
                     if (i > length)
                     {
                            str = str.Substring(0, j) + "...";
                            break;
                     }
                            j ++;
                     }
                     return str;

              }

在aspx文件里
<%# CutString(DataBinder.Eval(Container.DataItem, "uname"),10)

%>
方法3:
public FixStr(string str,int maxlength)
{
if(str.Length > maxlength)
{
return str.substring(0,maxlength) + "...";
}
else
{
return str;
}
}

//////////////////////////////////////////////////////////////////////
例子:
代码
public string FixStr(string str,int maxlength)
     {
       if(str.Length > maxlength)
       {
        return str.Substring(0,maxlength) + "...";
       }
       else
       {
       return str;
       }
页面显示调用
<asp:LinkButton ID="LinkButton1"  CommandName="showInfo" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"lvword_Id")%>' runat="server" Text='<%#FixStr( Eval("lvword_Content").ToString(),10) %>'></asp:LinkButton>
    }


只有注册用户登录后才能发表评论。


网站导航: