C#區分中英文按照指定長度擷取字串的方法
阿新 • • 發佈:2020-05-29
https://www.jb51.net/article/63086.htm
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 /// <summary> /// 擷取文字,區分中英文字元,中文算兩個長度,英文算一個長度 /// </summary> /// <param name="str">待擷取的字串</param> /// <param name="length">需計算長度的字串</param> /// <returns>string</returns> public static string GetSubString(string str,int length) { string temp = str; int j = 0; int k = 0; for (int i = 0; i < temp.Length; i++) { if (Regex.IsMatch(temp.Substring(i,1),@"[\u4e00-\u9fa5]+")) { j += 2; } else { j += 1; } if (j <= length) { k += 1; }if (j > length) { return temp.Substring(0,k) + ".."; } } return temp; }