获取字符串长度、字节长度、UTF-8字节长度(C#)

获取字符串长度、字节长度、UTF-8字节长度,

代码编写:

string str = "字符串长度测试12345+-=@#";
int test1 = str.Length;//字符串长度:不管中文、英文、符号都是一个字符
int test2 = System.Text.Encoding.Default.GetByteCount(str);//默认编码:中文占两个字节,其他占一个字节
int test3 = System.Text.Encoding.UTF8.GetByteCount(str);//UTF-8编码:中文占三个字节,其他占一个字节

Console.WriteLine("---------------字符串长度-----------------");
Console.WriteLine("test1长度:" + test1);
Console.WriteLine("test2长度(默认编码):" + test2);
Console.WriteLine("test3长度(UTF-8编码):" + test3);
Console.WriteLine("---------------字符串长度-----------------");

输出结果: