本文實(shí)例講述了C#按字節(jié)數(shù)截取字符串并在后面加上省略號(hào)...的方法,這是一個(gè)自定義的C#函數(shù),函數(shù)的使用說明如下:
<param name="origStr">原始字符串</param><param name="endIndex">提取前endIdex個(gè)字節(jié)</param><returns></returns>
函數(shù)代碼如下:
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;}以下所示示例也是根據(jù)字節(jié)數(shù)截取字符串的,只是這個(gè)函數(shù)后面不加省略號(hào)……
/// 按字節(jié)數(shù)截取字符串(不帶省略號(hào))/// </summary>/// <param name="origStr">原始字符串</param>/// <param name="endIndex">提取前endIdex個(gè)字節(jié)</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;}新聞熱點(diǎn)
疑難解答
圖片精選