tnblog
首页
视频
资源
登录

字符串扩展方法

2737人阅读 2020/3/31 14:54 总访问:342415 评论:0 收藏:0 手机
分类: ASP.NET

  1. 获取字符串的实际长度(按单字节)
    public static int GetRealLength(this string source)
    {
       return System.Text.Encoding.Default.GetByteCount(source);
    }
    取得固定长度的字符串(按单字节截取)
    public static string SubString(this string source, int resultLength)
    {
      //判断字串是否为空
      if (source == null)
       {
         return "";
      }
       //判断字符串长度是否大于截断长度
       if(System.Text.Encoding.Default.GetByteCount(source) > resultLength)
       {
         //初始化
         int i = 0, j = 0;
          //为汉字或全脚符号长度加2否则加1
         foreach (char newChar in source)
         {
           if ((int)newChar > 127)
            {
              i += 2;
           }
           else
           {
             i++;
           }
           if (i > resultLength)
           {
             source = source.Substring(0, j);
             break;
           }
             j++;
         }
       }
          return source;
    }
    取得固定长度字符的字符串,后面加上…(按单字节截取)
    public static string SubStr(this string source, int resultLength)
            {
                //判断字串是否为空
                if (string.IsNullOrEmpty(source))
                {
                    return "";
                }
                if (source.GetRealLength() <= resultLength)
                {
                    return source;
                }
                else
                {
                    return source.SubString(resultLength) + "...";
                }
            }
    取得固定长度字符的字符串(按单字节截取)(无添加...)
    public static string SubStrUnAdd(this string source, int resultLength)
            {
                //判断字串是否为空
                if (string.IsNullOrEmpty(source))
                {
                    return "";
                }
                if (source.GetRealLength() <= resultLength)
                {
                    return source;
                }
                else
                {
                    return source.SubString(resultLength);
                }
            }
评价
当你知道迷惑时,并不可怜,当你不知道迷惑时,才是最可怜的。
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
欢迎加群交流技术