您当前位置:编程帮手 > 知识 > 知识 > C# > String > 内容
代码库
2014-06-15 13:30:45 访问(5276) 赞(0) 踩(0)
/// /// 截取字符串(考虑中文两字节) /// /// 传入的字符串(如:传入的字符串) /// 截断的长度 /// 返回值(传入的字…) public static string CutString ( string inputString, int allowLen ) { if (allowLen < 0) return inputString; if (allowLen == 0) return string.Empty; // 链接符 // string AddShowStr = "…"; ASCIIEncoding ascii = new ASCIIEncoding(); int tempLen = 0; StringBuilder theResult = new StringBuilder(); byte[] s = ascii.GetBytes(inputString); int iLen = s.Length; // 判断 // for (int i = 0; i < iLen; i++) { if ((int)s[i] == 63) { tempLen += 2; } else { tempLen += 1; } // 等同长度 // if (tempLen == allowLen) { // 最后一个字符 // if (i == iLen - 1) { theResult.Append(inputString.Substring(i, 1)); } else { theResult.Append(AddShowStr); } break; } if (tempLen > allowLen) { theResult.Append(AddShowStr); break; } theResult.Append(inputString.Substring(i, 1)); } return theResult.ToString(); } /// /// 截取字符串(考虑中文两字节) /// /// 传入的字符串(如:传入的字符串) /// 截断的长度 /// 拼接的提示符(如…) /// 返回值(传入的字…) public static string CutString ( string inputString, int allowLen, string AddShowStr ) { if (allowLen < 0) return inputString; if (allowLen == 0) return string.Empty; ASCIIEncoding ascii = new ASCIIEncoding(); int tempLen = 0; StringBuilder theResult = new StringBuilder(); byte[] s = ascii.GetBytes(inputString); int iLen = s.Length; // 判断 // for (int i = 0; i < iLen; i++) { if ((int)s[i] == 63) { tempLen += 2; } else { tempLen += 1; } // 等同长度 // if (tempLen == allowLen) { // 最后一个字符 // if (i == iLen - 1) { theResult.Append(inputString.Substring(i, 1)); } else { theResult.Append(AddShowStr); } break; } if (tempLen > allowLen) { theResult.Append(AddShowStr); break; } theResult.Append(inputString.Substring(i, 1)); } return theResult.ToString(); }
上一条:
下一条: