分类:
ASP.NET
获取字符串的实际长度(按单字节) public static int GetRealLength(this string source) { return System.Text.Encoding.Default.GetByteCount(source); } 取得固定长度的字符串(按单字节截取) public static string SubString(this string source, int resultLength) { //判断字串是否为空 if (source == null) { return ""; } //判断字符串长度是否大于截断长度 if(System.Text.Encoding.Default.GetByteCount(source) > resultLength) { //初始化 int i = 0, j = 0; //为汉字或全脚符号长度加2否则加1 foreach (char newChar in source) { if ((int)newChar > 127) { i += 2; } else { i++; } if (i > resultLength) { source = source.Substring(0, j); break; } j++; } } return source; } 取得固定长度字符的字符串,后面加上…(按单字节截取) public static string SubStr(this string source, int resultLength) { //判断字串是否为空 if (string.IsNullOrEmpty(source)) { return ""; } if (source.GetRealLength() <= resultLength) { return source; } else { return source.SubString(resultLength) + "..."; } } 取得固定长度字符的字符串(按单字节截取)(无添加...) public static string SubStrUnAdd(this string source, int resultLength) { //判断字串是否为空 if (string.IsNullOrEmpty(source)) { return ""; } if (source.GetRealLength() <= resultLength) { return source; } else { return source.SubString(resultLength); } }
评价