C++字符串、字符数组长度

在 C++ 中常用的获取字符串长度或者字符串数组长度的函数有:

  • length()
  • size()
  • strlen()
  • sizeof()

str.length() 和 str.size() 用来求字符串(string 类型)的长度。

strlen(str) 是用于求字符数组的长度,其参数是char*。当数组名作为参数传入时,实际上数组就退化成指针了。

sizeof(str) 是运算符,在头文件中 typedef 为 unsigned int,其值在编译时即计算好了,参数可以是数组、指针、类型、对象、函数等。由于在编译时计算,因此 sizeof() 不能用来返回动态分配的内存空间的大小

1
2
3
4
5
6
7
8
9
10
11
12
13
string s1 = "01234";
char s2[10] = "0123456";
cout<<s1.length()<<endl;
cout<<s1.size()<<endl;
cout<<strlen(s2)<<endl;
cout<<sizeof(s2)<<endl;
cout<<sizeof(s1)<<endl;
// 输出
5
5
7
10
8
文章作者: gzwangu
文章链接: https://gzwangu.github.io/2020/08/20/C-字符串、字符数组长度/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Clousbin の Blog
支付宝打赏
微信打赏