C++中三种函数的区别
length()函数
size()函数
strlen()函数
sizeof()函数
length()函数
length()函数用来获取字符串长度。
string s = "hello";
int len = s.length();
cout << "len = " << len << endl;
输出为:len = 5
size()函数
跟length()函数一样,可以获得字符串长度。但是size()函数还可以用来获取vector的长度。
string s = "hello";
vector<int> nums = {1,2,3,4};
int len1 = s.length();
int len2 = nums.size();
cout << "len1 = " << len1 << endl;
cout << "len2 = " << len2 << endl;
输出为:len1 = 5 len2 = 4
strlen()函数
只能用来计算字符型数组的长度。
char s[30] = "abcdefg";
int len = strlen(s);
cout << "len = " << len << endl;
输出为:len = 7
sizeof()函数
sizeof()是操作符,用来获取对象所占内存字节大小。
char s[30] = "abcdefg";
int n = sizeof(s);
cout << "n = " << n << endl;
输出为:n = 30