99网
您的当前位置:首页文字字符串长度截取

文字字符串长度截取

来源:99网

        /// <summary>
        /// 截取指定字节长度的字符串最标准做法(超出时只记下上一个有效位置)
        /// </summary>
        /// <param name="str">原字符串</param>
        /// <param name="len">截取字节长度</param>
        /// <returns></returns>
        public static string CutByteString(string str, int len)
        {
            string result = string.Empty;// 最终返回的结果
            if (string.IsNullOrEmpty(str)) { return result; }
            int byteLen = System.Text.Encoding.Default.GetByteCount(str);// 单字节字符长度
            int charLen = str.Length;// 把字符平等对待时的字符串长度
            int byteCount = 0;// 记录读取进度
            int pos = 0;// 记录截取位置
            if (byteLen > len)
            {
                for (int i = 0; i < charLen; i++)
                {
                    if (Convert.ToInt32(str.ToCharArray()[i]) > 255)// 按中文字符计算加2
                    { byteCount += 2; }
                    else// 按英文字符计算加1
                    { byteCount += 1; }
                    if (byteCount > len)// 超出时只记下上一个有效位置
                    {
                        pos = i;
                        break;
                    }
                    else if (byteCount == len)// 记下当前位置
                    {
                        pos = i + 1;
                        break;
                    }
                }
                if (pos >= 0)
                { result = str.Substring(0, pos); }
            }
            else
            { result = str; }
            return result;
        }

 

//取得字符串长度 

    static int StrLength(string str)
    {
        int len = 0;
        byte[] b;

        for (int i = 0; i < str.Length; i++)
        {
            b = Encoding.Default.GetBytes(str.Substring(i, 1));
            if (b.Length > 1)
                len += 2;
            else
                len++;
        }

        return len;
    }

 

 

//截取字符串

    static string StrCut(string str, int length)
    {
        int len = 0;
        byte[] b;
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < str.Length; i++)
        {
            b = Encoding.Default.GetBytes(str.Substring(i, 1));
            if (b.Length > 1)
                len += 2;
            else
                len++;

            if (len >= length)
                break;

            sb.Append(str[i]);
        }

        return sb.ToString();
    }

 

     //截取字符串

      public static string GetFirstString(string stringToSub, int length)
       {           
           Regex regex = new Regex("[\u4e00-\u9fa5]+", RegexOptions.Compiled);
           char[] stringChar = stringToSub.ToCharArray();
           StringBuilder sb = new StringBuilder();
           int nLength = 0;
           bool isCut = false;
           for (int i = 0; i < stringChar.Length; i++)
           {
               if (regex.IsMatch((stringChar[i]).ToString()))
               {
                   sb.Append(stringChar[i]);
                   nLength += 2;
               }
               else
               {
                   sb.Append(stringChar[i]);
                   nLength = nLength + 1;
               }

               if (nLength > length)
               {
                   isCut = true;
                   break;
               }
           }
           if (isCut)
               return sb.ToString() + "..";
           else
               return sb.ToString();           
       }

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+"...");
       }
   }

 

 

JS:

byteLength:数据库字节长度
title:字段中文名称
attribute:属性名称(固定为:this)
使用方法说明:

(1)在文本对象中添加onkeyup事件: οnkeyup="limitLength(this,'名称',100)"即可。 

    <script type="text/javascript">
        function limitLength(attribute, title, byteLength) {
            //var byteLength=8;
            //alert(attribute);
            var count = 0;
            //alert(count);
            var value = attribute.value;
            var newvalue = value.replace(/[^\x00-\xff]/g, "**");
            var length = newvalue.length;
            //alert(newvalue);
            //当填写的字节数小于设置的字节数
            if (length * 1 <= byteLength * 1) {
                return;
            }
            var limitData = newvalue.substr(0, byteLength);
            //alert(limitData);
            var count = 0;
            var limitvalue = "";
            for (var i = 0; i < limitData.length; i++) {
                var flat = limitData.substr(i, 1);
                if (flat == "*") {
                    count++;
                }
            }
            //alert(count);
            var size = 0;
            var istar = newvalue.substr(byteLength * 1 - 1, 1); //校验点是否为“×”

            //if 基点是×; 判断在基点内有×为偶数还是奇数
            if (count % 2 == 0) {
                //当为偶数时
                size = count / 2 + (byteLength * 1 - count);
                limitvalue = value.substr(0, size);
            } else {
                //当为奇数时
                size = (count - 1) / 2 + (byteLength * 1 - count);
                limitvalue = value.substr(0, size);
            }
            alert(title + "最大输入" + byteLength + "个字节(相当于" + byteLength / 2 + "个汉字)!");
            attribute.value = limitvalue;
            attribute.focus();
            return;
        }
    </script>

 function cutstr(str,len)
{
   var str_length = 0;
   var str_len = 0;
      str_cut = new String();
      str_len = str.length;
      for(var i = 0;i<str_len;i++)
     {
        a = str.charAt(i);
        str_length++;
        if(escape(a).length > 4)
        {
         //中文字符的长度经编码之后大于4
         str_length++;
         }
         str_cut = str_cut.concat(a);
         if(str_length>=len)
         {
         str_cut = str_cut.concat("...");
         return str_cut;
         }
    }
    //如果给定字符串小于指定长度,则返回源字符串;
    if(str_length<len){
     return  str;
    }
}

 

因篇幅问题不能全部显示,请点此查看更多更全内容