在程序中总是会有需要按照字节数来限制用户输入的字符数量的需求,网上这种需求的解法也各种各样,在这里我找到一个较为简单的做法.
当一个字符串进来时我们只需要判断他的每个字符的字节数是否和字符数相等就可以知道这个字符是不是双字节的字符了.
具体代码如下:
static void Main(string[] args) { while (true) { Console.Write("输入字符:"); string c = Console.ReadLine(); int count = 0; for (int i = 0; i < c.Length; i++) { string t = c.Substring(i, 1); count += Encoding.Default.GetByteCount(t) != t.Length ? 2 : 1; } Console.WriteLine("字节长度:{0}", count); } }
下面这段是javascript的,做法是判断字符是否在ACSII编码之内
代码如下:
function strByteLenth(str) { if(!str) { return 0; } //预期计数:中文2字节,英文1字节 var c = 0; for (var i=0;i<str.length;i++) { if (str.charCodeAt(i)>255) { //按照预期计数增加2 c+=2; } else { c++; } } return c; }