本文實例講述了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;}
新聞熱點
疑難解答