C/C++ length()、size()、strlen()、sizeof() 用法区分

  • length() 仅用于 求 字符串 长度

  • size() 用于 求 1.字符串 2.vector类型 长度

  • strlen() 用于 求 字符串/字符数组 的长度,直到空结束字符,但不包括空结束字符。

  • sizeof() 用于 求 对象所占内存空间的大小 (即 所占的字节数)

sizeof()/sizeof(数组类型) 用于 求 数组大小
// 举例:
int a[3];  
cout << sizeof(a)/sizeof(int);  // Output: 3
cout << sizeof(a)/sizeof(a[0]);  // Output: 3
#include<iostream>
#include<cstring>
#include<vector>
using namespace std;

int main()
{
    int a[5] = {1, 2, 3};
    cout << sizeof(a) << endl;                   // Output: 20    // int类型每个字符占4个字节符 ,数组大小为5, 4*5=20
    cout << sizeof(a) / sizeof(a[0]) << endl;    // Output: 5    //求得数组大小为5
    cout << sizeof(a) / sizeof(int) << endl;    // Output: 5    //求得数组大小为5

	string str1 = "a";
    cout << sizeof(str1) << endl; // Output: 32
    string str2 = "ab";
    cout << sizeof(str2) << endl; // Output: 32    
    string str3 = "abcd";
    cout << sizeof(str3) << endl; // Output: 32

    char ch[30];
    strcpy(ch, "This is a.com");
    cout << strlen(ch) << endl;  // Output: 13

    vector<int> num(15, 2);
    cout << num.size() << endl;   // Output: 15


    string str = "abcdefg";
    cout << str.size() << endl;   // Output: 7
    cout << str.length() << endl;  // Output: 7
    
    return 0;
}

Note: 自己总结的,如有不当之处,恳请指正,感谢!

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值