C#中英文混合字符串截取函数
程序员文章站
2024-02-18 15:37:58
代码一
///
/// 截断字符串
///
///
代码一
/// <summary> /// 截断字符串 /// </summary> /// <param name="maxlength">最大长度</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# 截取字符串方法(包含中英混合)的实现代码,需要的朋友可以参考一下
上一篇: PHP实现冒泡排序的简单实例
下一篇: C# Socket粘包处理讲解示例