当前位置:首页 > Windows程序 > 正文

c#的中英文混合字符串截取

2021-03-28 Windows程序

public class StringHelper     {         public static string GetSubString(string str, int len)         {             string result = string.Empty;// 最终返回的结果             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;         }

/// <summary>         /// c#的中英文混合字符串截取         /// </summary>         /// <param></param>         /// <param>显示的字符长度*2</param>         /// <returns></returns>         public static string SubString(string inputString, int length)         {             byte[] ping = Encoding.UTF8.GetBytes(inputString);             int count=Encoding.UTF8.GetByteCount(inputString);             if (count <= length * 2)             {                 return inputString;             }             ASCIIEncoding ascii = new ASCIIEncoding();             int tempLen = 0;             string tempString = "";             byte[] s = ascii.GetBytes(inputString);             for (int i = 0; i < s.Length; i++)             {                 ////判断是否为汉字或全脚符号                 if ((int)s[i] == 63)                 {                     tempLen += 2;                 }                 else                 {                     tempLen += 1;                 }                 tempString += inputString.Substring(i, 1);                 if (tempLen >= length * 2)                     break;             }             return tempString;         }

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/69379.html