1、char指针引导的字符数组:
strlen返回字符数组的长度,包括空格。
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
const char* p = "hell o"; //因为"hell o"是常量型的,所以要加const
cout<<strlen(p);
return 0;
}
结果:
2、char数组:
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char p[] = "hell o";
cout<<strlen(p);
return 0;
}
结果:
3、string字符串的长度:
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
string p = "hell o";
cout<<p.length();
return 0;
}
结果:
4、char数组结束符 \0:
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
const char* p = "hel\0l o";
cout<<strlen(p);
return 0;
}
结果:
5、string字符串结束符 \0:
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
string p = "hel\0l o";
cout<<p.length();
return 0;
}
结果:
小结:
无论char数组,还是string字符串,都不是以空格,不是以换行(\n)作为结束符,而是以 \0 作为结束符。