关于string的length

Posted tobe professional

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于string的length相关的知识,希望对你有一定的参考价值。

在C++里面,std::string的length()返回的是字节数,与编码方式有关。

1 int main()
2 {
3     std::string s = "我是中国人";
4     std::cout << s.length() << std::endl;
5     std::cout << strlen(s.c_str()) << std::endl;
6 }

上面的代码,使用GB2312编码,输出结果是10和10.

而在C#里面,string.Length属性返回的是字符数,与编码方式无关。

1         static void Main(string[] args)
2         {
3             string s = "我是中国人";
4             Console.WriteLine(s.Length);
5             Console.WriteLine(Encoding.UTF8.GetBytes(s).Length);
6         }

上面代码输出结果是5和15.

 

以上是关于关于string的length的主要内容,如果未能解决你的问题,请参考以下文章