C#實(shí)現(xiàn)根據(jù)字節(jié)數(shù)截取字符串并加上省略號的方法
更新時(shí)間:2014年07月30日 11:22:44 投稿:shichen2014
這篇文章主要介紹了C#實(shí)現(xiàn)根據(jù)字節(jié)數(shù)截取字符串并加上省略號的方法,比較實(shí)用的功能,需要的朋友可以參考下
本文實(shí)例講述了C#按字節(jié)數(shù)截取字符串并在后面加上省略號...的方法,這是一個(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ù)后面不加省略號……
/// 按字節(jié)數(shù)截取字符串(不帶省略號) /// </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; }
相關(guān)文章
WPF實(shí)現(xiàn)圖片合成或加水印的方法【2種方法】
這篇文章主要介紹了WPF實(shí)現(xiàn)圖片合成或加水印的方法,結(jié)合實(shí)例形式分析了2種比較實(shí)用的WPF圖片操作相關(guān)技巧,需要的朋友可以參考下2017-03-03C#實(shí)現(xiàn)的SN快速輸入工具實(shí)例
這篇文章主要介紹了C#實(shí)現(xiàn)的SN快速輸入工具,以實(shí)例的形式詳細(xì)講述了C#實(shí)現(xiàn)序列號快速輸入的方法,是非常實(shí)用的技巧,需要的朋友可以參考下2014-11-11C#實(shí)現(xiàn)NPOI的Excel導(dǎo)出詳解
這篇文章主要介紹了C#實(shí)現(xiàn)NPOI的Excel導(dǎo)出的示例代碼,文中的實(shí)現(xiàn)過程講解詳細(xì),對我們的學(xué)習(xí)或工作有一定的幫助,感興趣的可以跟隨小編一起學(xué)習(xí)一下2022-01-01