一个容易失误的字符串转字符问题

 1  class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             string testStr = "的房间垃圾发电阿什利发水立方啊";
 6             char[] charstr = testStr.ToCharArray();
 7             int temp1 = charstr.Length;
 8             int temp2 = Console.OutputEncoding.GetBytes(charstr).Length;
 9             Console.WriteLine("testStr字长:{0}", temp1);
10             Console.WriteLine("testStr字长:{0}", temp2);
11             Console.ReadKey();
12         }
13         public static void Print()
14         {
15             while (true)
16             {
17                 Console.WriteLine("CPU当前使用率:{0}", CpuHelper.CpuRate);
18             }
19         }
20     }
View Code

上面的结果为:

testStr字长:15

testStr字长:30

结果分析:String.ToCharArray().length 只是把字符串一个个切割成字符后的字符个数,而Console.OutputEncoding.GetBytes(charstr).Length是把字符串转换成字节后的长度 。另外          

 汉字的长度为2字节,所以出现两倍的情况。当字符串不包含汉字的时候,结果是一样。

原文地址:https://www.cnblogs.com/liehuochongsheng/p/3757616.html