ASP.NET截取字符串

#region 格式化字符串,取字符串前 strLength 位,其他的用...代替.计算字符串长度。汉字两个字节,字母一个字节FormatString(string str,int len)

              /// <summary>

              /// 格式化字符串,取字符串前 strLength 位,其他的用...代替.计算字符串长度。汉字两个字节,字母一个字节

              /// </summary>

              /// <param name="str">字符串</param>

              /// <param name="strLength">字符串长度</param>

              /// <returns></returns>

              public static string FormatStr(string str,int len)

              {                    

                     ASCIIEncoding ascii = new ASCIIEncoding();

                     int tempLen=0;

                     string tempString="";

                     byte[] s = ascii.GetBytes(str);

                     for(int i=0;i<s.Length;i++)

                     {

                            if((int)s[i]==63)

                            {

                                   tempLen+=2;

                            }

                            else

                            {

                                   tempLen+=1;

                            }



                            try

                            {

                                   tempString+=str.Substring(i,1);

                            }

                            catch

                            {

                                   break;

                            }



                            if(tempLen>len)

                                   break;

                     }

                     //如果截过则加上半个省略号

                     byte[] mybyte=System.Text.Encoding.Default.GetBytes(str);

                     if(mybyte.Length>len)

                            tempString+="...";



                     tempString=tempString.Replace(" ","  ");

                     tempString=tempString.Replace("<","<");

                     tempString=tempString.Replace(">",">");

                     tempString=tempString.Replace('\n'.ToString(),"<br>");

                     return tempString;



              }

              #endregion
原文地址:https://www.cnblogs.com/ggbbeyou/p/1639595.html