C#完成依據字節數截取字符串並加上省略號的辦法。本站提示廣大學習愛好者:(C#完成依據字節數截取字符串並加上省略號的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C#完成依據字節數截取字符串並加上省略號的辦法正文
本文實例講述了C#按字節數截取字符串並在前面加上省略號...的辦法,這是一個自界說的C#函數,函數的應用解釋以下:
<param name="origStr">原始字符串</param> <param name="endIndex">提取前endIdex個字節</param> <returns></returns>
函數代碼以下:
public static string GetSubString(string origStr, int endIndex) { if (origStr == null || origStr.Length == 0 || endIndex < 0) return ""; int bytesCount = System.Text.Encoding.GetEncoding("gb2312").GetByteCount(origStr); if (bytesCount > endIndex) { int readyLength = 0; int byteLength; for (int i = 0; i < origStr.Length; i++) { byteLength = System.Text.Encoding.GetEncoding("gb2312").GetByteCount(new char[] { origStr[i] }); readyLength += byteLength; if (readyLength == endIndex) { origStr = origStr.Substring(0, i + 1) + "..."; break; } else if (readyLength > endIndex) { origStr = origStr.Substring(0, i) + "..."; break; } } } return origStr; }
以下所示示例也是依據字節數截取字符串的,只是這個函數前面不加省略號……
/// 按字節數截取字符串(不帶省略號) /// </summary> /// <param name="origStr">原始字符串</param> /// <param name="endIndex">提取前endIdex個字節</param> /// <returns></returns> public static string GetSub1String(string origStr, int endIndex) { if (origStr == null || origStr.Length == 0 || endIndex < 0) return ""; int bytesCount = System.Text.Encoding.GetEncoding("gb2312").GetByteCount(origStr); if (bytesCount > endIndex) { int readyLength = 0; int byteLength; for (int i = 0; i < origStr.Length; i++) { byteLength = System.Text.Encoding.GetEncoding("gb2312").GetByteCount(new char[] { origStr[i] }); readyLength += byteLength; if (readyLength == endIndex) { origStr = origStr.Substring(0, i + 1); break; } else if (readyLength > endIndex) { origStr = origStr.Substring(0, i); break; } } } return origStr; }