当前位置导航:炫浪网>>网络学院>>网页制作>>ASP教程

截取固定长度字符串显示在页面

以下是代码,呵呵,比较简单,主要是区分汉字和字母,不然一个全是字母,一个全是汉字的两条记录排列在一起时会比较难看,全字符的长度只有全汉字 的一半就显示...号了
     public static string stringformat(string str,int n)
                {
                        ///
                        ///格式化字符串长度,超出部分显示省略号,区分汉字跟字母。汉字2个字节,字母数字一个字节
                        ///
                        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&&t<n;i++)
                                {
                                        if((int)q[i]>=0x4E00 && (int)q[i]<=0x9FA5)//是否汉字
                                        {
                                                temp+=q[i];
                                                t+=2;
                                        }
                                        else
                                        {
                                                temp+=q[i];
                                                t++;
                                        }
                                }
                                return (temp+"...");
                        }
               
                }
相关内容
赞助商链接