-
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: 自己总结的,如有不当之处,恳请指正,感谢!