zoukankan      html  css  js  c++  java
  • 截取字符串的长度(中英文)

    } } return System.Text.Encoding.Unicode.GetString(list.ToArray()); } /// /// 要截取的字节数 /// ///输入的字符串 ///限定长度 ///是否需要省略号,true--需要,false--不需要 ///截取类型 ///截取后的字符串,如果是NVarchar--则20个字节就会有10个字符,Varchar--20个字节会有>=10个字符 public static string CutString(string value, int length, bool ellipsis, CutType cuttype) { value = value.Trim(); if (value.Length == 0) return string.Empty; if (cuttype == CutType.NVarchar) { if (value.Length > length / 2) { value = value.Substring(0, length / 2); if (ellipsis) return value + ".."; } } else { string resultString = string.Empty; byte[] myByte = System.Text.Encoding.GetEncoding("gbk").GetBytes(value); if (myByte.Length > length) { resultString = Encoding.GetEncoding("gbk").GetString(myByte, 0, length); string lastChar = resultString.Substring(resultString.Length - 1, 1); if (lastChar.Equals(value.Substring(resultString.Length - 1, 1))) { value = resultString; }//如果截取后最后一个字符与原始输入字符串中同一位置的字符相等,则表示截取完成 else//如果不相等,则减去一个字节再截取 { value = Encoding.GetEncoding("gbk").GetString(myByte, 0, length - 1); } if (ellipsis) return value + ".."; return value; } } return value; } #region 截短字串的函数,分区中英文 /// /// 截短字串的函数 /// ///要加工的字串 ///长度 /// 被加工过的字串 public static string Left(string mText, int byteCount) { if (byteCount < 1) return mText; if (System.Text.Encoding.Default.GetByteCount(mText) <= byteCount) { return mText; } else { byte[] txtBytes = System.Text.Encoding.Default.GetBytes(mText); byte[] newBytes = new byte[byteCount - 4]; for (int i = 0; i < byteCount - 4; i++) { newBytes[i] = txtBytes[i]; } string OutPut = System.Text.Encoding.Default.GetString(newBytes) + "..."; if (OutPut.EndsWith("?...") == true) { OutPut = OutPut.Substring(0, OutPut.Length - 4); OutPut += "..."; } return OutPut; } } #endregion } /// /// 截取字符枚举值,Varchar--英文一个字节,中文两个字节,NVarchar--无论中英文都是两个字节 /// public enum CutType { Varchar, NVarchar }

  • 相关阅读:
    day24 Pyhton学习 反射
    正则表达式练习
    day23 Pyhton学习 昨日回顾.re模块.序列化模块
    day22 函数整理
    day22 Pyhton学习 re模块和正则表达式
    day21 Pyhton学习 模块
    函数整理
    一个关于浮点数运算需要注意的地方
    关于逻辑运算案例笔记
    数据的表现形式和进制之间的转换
  • 原文地址:https://www.cnblogs.com/DTWolf/p/4670002.html
Copyright © 2011-2022 走看看