根据字节长度截取字符串

1 public string SubStrByByteLength(string str, int bytesLength) 2 { 3 if (Encoding.Default.GetByteCount(str) <= bytesLength) 4 { 5 return str; 6 } 7 else 8 { 9 string _tempStr = string.Empty; 10 11 int _tempLength = 0; 12 13 char[] chrs = str.ToCharArray(); 14 15 foreach (char chr in chrs) 16 { 17 _tempLength += Encoding.Default.GetByteCount(chr.ToString()); 18 19 if (_tempLength > bytesLength) 20 { 21 break; 22 } 23 24 _tempStr += chr; 25 } 26 27 return _tempStr; 28 } 29 }