C#字符串截取(区分汉字)(转)
- /// <summary>
- /// 截取字符串
- /// </summary>
- /// <param name="inputString">原始字符串</param>
- /// <param name="length">截取长度</param>
- /// <returns>截取后的字符串</returns>
- public static string SubString(string inputString, int length)
- {
- if(Encoding.UTF8.GetByteCount(inputString)<=length*2)
- {
- return inputString;
- }
- ASCIIEncoding ascii = new ASCIIEncoding();
- int tempLen = 0;
- string tempString = "";
- byte[] s = ascii.GetBytes(inputString);
- for (int i = 0; i < s.Length; i++)
- {
- if ((int)s[i] == 63)
- {
- tempLen += 2;
- }
- else
- {
- tempLen += 1;
- }
- tempString += inputString.Substring(i, 1);
- if (tempLen >= (length-1)*2)
- break;
- }
- //如果截过则加上半个省略号
- if (System.Text.Encoding.Default.GetBytes(inputString).Length > length)
- tempString += "..";
- return tempString;
- }
可不要忘记导入System.Text命名空间哦
适合 asp.net ,c# ,Wpf.