C# 按不同的字节编码,通过字节数去截取字符串
/// <summary> /// 按不同的字节编码,通过字节数去截取字符串 /// 数据库UTF-8 1个数字、字母、英文符号算1个长度 1个中文、中文符号算3个长度 /// </summary> /// <param name="origStr">需截取的字符串</param> /// <param name="bytesLength">需截取的字节长度</param> /// <param name="dstEncoding">截取的字节编码类型</param> /// <returns></returns> public static string GetSubString(string origStr, int bytesLength, Encoding dstEncoding) { if (origStr == null || origStr.Length == 0 || bytesLength < 0) return ""; int bytesCount = dstEncoding.GetByteCount(origStr); if (bytesCount > bytesLength) { int readyLength = 0; int byteLength; for (int i = 0; i < origStr.Length; i++) { byteLength = dstEncoding.GetByteCount(new char[] { origStr[i] }); readyLength += byteLength; if (readyLength == bytesLength) { origStr = origStr.Substring(0, i + 1);// + "..."; 加省略号 break; } else if (readyLength > bytesLength) { origStr = origStr.Substring(0, i);// + "..."; 加省略号 break; } } } return origStr; }
sting newStr = GetSubString(origStr, bytesLength, Encoding.UTF8);
作者:陈哲Gilbert
出处:http://gilbert.cnblogs.com
版权声明:
本文版权归作者所有,欢迎转载,请在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。