c#的中英文混合字符串截取
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 name="inputString"></param> /// <param name="length">显示的字符长度*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; }
public static string GetSub(string sub, int length) { //byte[] bytStr = System.Text.Encoding.Default.GetBytes(sub); if (sub == null) return string.Empty; int len = length * 2; //aequilateLength为中英文等宽长度,cutLength为要截取的字符串长度 int aequilateLength = 0, cutLength = 0; Encoding encoding = Encoding.GetEncoding("gb2312");
string cutStr = sub.ToString(); int strLength = cutStr.Length; byte[] bytes; for (int i = 0; i < strLength; i++) { bytes = encoding.GetBytes(cutStr.Substring(i, 1)); if (bytes.Length == 2)//不是英文 aequilateLength += 2; else aequilateLength++;
if (aequilateLength <= len) cutLength += 1;
if (aequilateLength > len) return cutStr.Substring(0, cutLength);//+ "..." } return cutStr; }
}