C#实现根据字节数截取字符串并加上省略号的方法
程序员文章站
2023-12-18 15:54:28
本文实例讲述了c#按字节数截取字符串并在后面加上省略号...的方法,这是一个自定义的c#函数,函数的使用说明如下:
本文实例讲述了c#按字节数截取字符串并在后面加上省略号...的方法,这是一个自定义的c#函数,函数的使用说明如下:
<param name="origstr">原始字符串</param> <param name="endindex">提取前endidex个字节</param> <returns></returns>
函数代码如下:
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; }
以下所示示例也是根据字节数截取字符串的,只是这个函数后面不加省略号……
/// 按字节数截取字符串(不带省略号) /// </summary> /// <param name="origstr">原始字符串</param> /// <param name="endindex">提取前endidex个字节</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; }