幽梦紫曦

字符串扩展方法

电脑版发表于:2020/3/31 14:54

  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);
                }
            }
关于TNBLOG
TNBLOG,技术分享。技术交流:群号677373950
ICP备案 :渝ICP备18016597号-1
App store Android
精彩评论
{{item.replyName}}
{{item.content}}
{{item.time}}
{{subpj.replyName}}
@{{subpj.beReplyName}}{{subpj.content}}
{{subpj.time}}
猜你喜欢