string如果直接获取Length是无法区分中英文还有字符之间的区别。以下方法可以识别中文长度为2,英文字符为1。
class Program { static void Main(string[] args) { //长度为5 GetStrLength("嘻嘻x"); Console.ReadKey(); } //获取长度方法 private static int GetStrLength(string str) { if (string.IsNullOrEmpty(str)) return 0; ASCIIEncoding ascii = new ASCIIEncoding(); int tempLen = 0; byte[] s = ascii.GetBytes(str); for (int i = 0; i < s.Length; i++) { if ((int)s[i] == 63) { tempLen += 2; } else { tempLen += 1; } } return tempLen; }