strlen(a):
在<cstring>头文件中,用于字符数组和字符串,返回的是字符串的长度,不会算上结束位置的'\0'。
#include <iostream>
// #include <iomanip>
#include <cstring>
using namespace std;
int main()
{
char b[10]="hello";
cout<<strlen(b);//结果5
return 0;
}
strlen() 函数计算的是字符串的实际长度,遇到第一个'\0'结束。如果你只定义没有给它赋初值,这个结果是不定的,它会从首地址一直找下去,直到遇到'\0'停止。
如果字符的个数等于字符数组的大小,那么strlen()的返回值就无法确定了,例如
char str[6] = "abcxyz";
strlen(str)的返回值将是不确定的。因为str的结尾不是0,strlen()会继续向后检索,直到遇到'\0',而这些区域的内容是不确定的。
sizeof(a):
返回数组所占内存空间的字节数
#include <iostream>
// #include <iomanip>
// #include <cstring>
using namespace std;
int main()
{
int a[10],x;
char b[10]="hello";
cout<<sizeof(a)<<endl<<sizeof(x)<<endl<<sizeof(b);
return 0;
}
根据数组的总内存空间除以每个数据需要占的内存空间可以获得数组的长度
#include <iostream>
// #include <iomanip>
// #include <cstring>
using namespace std;
int main()
{
int a[10];
cout<<sizeof(a)/sizeof(a[0]);//结果是10
return 0;
}
a.size(),a.length():
在<cstring><string>头文件中,用于string类型的数据,两个函数的作用几乎一致,都是返回字符串的长度
#include <iostream>
// #include <iomanip>
#include <cstring>
using namespace std;
int main()
{
string s="hello";
cout<<s.length();//结果是5
cout<<s.size();//结果是5
// char b[10]="hello";
// cout<<b.leghth();//不允许
return 0;
}