C#中英文混合字符串截取函數(shù)
代碼一
/// <summary> /// 截?cái)嘧址? /// </summary> /// <param name="maxLength">最大長(zhǎng)度</param> /// <param name="str">原字符串</param> /// <returns></returns> public static string CutStr(int maxLength, string str) { string temp = str; if (Regex.Replace(temp, "[\u4e00-\u9fa5]", "zz", RegexOptions.IgnoreCase).Length <= maxLength) { return temp; } for (int i = temp.Length; i >= 0; i--) { temp = temp.Substring(0, i); if (Regex.Replace(temp, "[\u4e00-\u9fa5]", "zz", RegexOptions.IgnoreCase).Length <= maxLength - 3) { return temp + "..."; } } return "..."; }
代碼二
private string GetByteString(string center, int maxlen, string endStr) { string temp = center.Substring(0, (center.Length < maxlen + 1) ? center.Length : maxlen + 1); byte[] encodedBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(temp); string outputStr = ""; int count = 0; for (int i = 0; i < temp.Length; i++) { if ((int)encodedBytes[i] == 63) count += 2; else count += 1; if (count <= maxlen - endStr.Length) outputStr += temp.Substring(i, 1); else if (count > maxlen) break; } if (count <= maxlen) { outputStr = temp; endStr = ""; } outputStr += endStr; return outputStr; }
以上就是C# 截取字符串方法(包含中英混合)的實(shí)現(xiàn)代碼,需要的朋友可以參考一下
- C#(.net)中按字節(jié)數(shù)截取字符串最后出現(xiàn)亂碼問(wèn)題的解決
- C# 字符串、數(shù)組和List的截取和轉(zhuǎn)換實(shí)例
- C#中按字符串截取長(zhǎng)字符串實(shí)例
- C#字符串的截取函數(shù)用法總結(jié)
- C#實(shí)現(xiàn)左截取和右截取字符串實(shí)例
- C#實(shí)現(xiàn)中英文混合字符串截取的方法
- C#實(shí)現(xiàn)根據(jù)字節(jié)數(shù)截取字符串并加上省略號(hào)的方法
- C#截取中英文混合指定長(zhǎng)度字符串實(shí)例
- C#幾種截取字符串的方法小結(jié)
- C#中截取字符串的的基本方法詳解
相關(guān)文章
C#結(jié)合數(shù)據(jù)庫(kù)的數(shù)據(jù)采集器示例
這篇文章主要介紹了C#結(jié)合數(shù)據(jù)庫(kù)的數(shù)據(jù)采集器,功能比較實(shí)用,需要的朋友可以參考下2014-07-07C#中Request.Cookies 和 Response.Cookies 的區(qū)別分析
本文通過(guò)實(shí)例代碼向我們展示了C#中Request.Cookies 和 Response.Cookies 的區(qū)別,文章淺顯易懂,這里推薦給大家。2014-11-11C# List 并發(fā)丟數(shù)據(jù)問(wèn)題原因及解決方案
這篇文章主要介紹了C# List 并發(fā)丟數(shù)據(jù)問(wèn)題原因及解決方案,幫助大家更好的理解和使用c#,感興趣的朋友可以了解下2021-02-02C#獲取系統(tǒng)當(dāng)前日期和時(shí)間的示例詳解
這篇文章主要為大家詳細(xì)介紹了C#如何使用DateTime的Now靜態(tài)屬性動(dòng)態(tài)獲得系統(tǒng)當(dāng)前日期和時(shí)間,文中的示例代碼講解詳細(xì),有需要的小伙伴可以參考一下2024-01-01C#實(shí)現(xiàn)簡(jiǎn)單的計(jì)算器功能
這篇文章主要為大家詳細(xì)介紹了C#實(shí)現(xiàn)簡(jiǎn)單的計(jì)算器功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-01-01c#中(int)、int.Parse()、int.TryParse、Convert.ToInt32的區(qū)別詳解
這篇文章主要介紹了c#中(int)、int.Parse()、int.TryParse、Convert.ToInt32的區(qū)別,需要的朋友可以參考下2014-07-07