/// /// 按不同的位元組編碼,通過位元組數去截取字元串 /// 資料庫UTF-8 1個數字、字母、英文符號算1個長度 1個中文、中文符號算3個長度 /// /// 需截取的字元串 /// 需截取的位元組長度 /// 截取的位元組編碼類型 /// ... ...
/// <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);