C# 按不同的字节编码,通过字节数去截取字符串
程序员文章站
2022-05-13 23:45:06
/// /// 按不同的字节编码,通过字节数去截取字符串 /// 数据库UTF-8 1个数字、字母、英文符号算1个长度 1个中文、中文符号算3个长度 /// /// 需截取的字符串 /// 需截取的字节长度 /// 截取的字节编码类型 /// ... ......
/// <summary> /// 按不同的字节编码,通过字节数去截取字符串 /// 数据库utf-8 1个数字、字母、英文符号算1个长度 1个中文、中文符号算3个长度 /// </summary> /// <param name="origstr">需截取的字符串</param> /// <param name="byteslength">需截取的字节长度</param> /// <param name="dstencoding">截取的字节编码类型</param> /// <returns></returns> public static string getsubstring(string origstr, int byteslength, encoding dstencoding) { if (origstr == null || origstr.length == 0 || byteslength < 0) return ""; int bytescount = dstencoding.getbytecount(origstr); if (bytescount > byteslength) { int readylength = 0; int bytelength; for (int i = 0; i < origstr.length; i++) { bytelength = dstencoding.getbytecount(new char[] { origstr[i] }); readylength += bytelength; if (readylength == byteslength) { origstr = origstr.substring(0, i + 1);// + "..."; 加省略号 break; } else if (readylength > byteslength) { origstr = origstr.substring(0, i);// + "..."; 加省略号 break; } } } return origstr; }
sting newstr = getsubstring(origstr, byteslength, encoding.utf8);