strlen() 只能够计算字符数组的长度
如:
char str[]="hello";
cout<<strlen(str);
输出为5,虽然在内存中长度为6,还有一个停止符 ’\0‘ 但是只计算实际长度
length() 计算字符串变量的函数
如:
string s1=“hello”;
cout<<s1.length();
输出应为5,计算长度也不包括 ’\0‘
sizeof() 函数计算字符串或者字符数组在内存中的实际长度
如:
char str[20]="hello";
cout<<strlen(str)<<endl;
cout<<siezeof(str)<<endl;
</pre><span style="font-size:18px">strlen() 输出为5 sizeof()输出为20,因为str开辟的长度就是20</span><p><span style="font-size:18px">如果 char str[]="hello" 没有限制str的长度,则sizeof()输出为6,包含了’\0‘</span></p><p><span style="font-size:18px"></span></p><p><span style="font-size:18px">再如:</span></p><p></p><pre code_snippet_id="623755" snippet_file_name="blog_20150320_4_6298191" name="code" class="cpp">string str="hello";
cout<<str.length()<<endl;
cout<<sizeof(str)<<endl;
length() 函数输出为5 sizeof()函数输出为32,(string字符串内存中长度为32,char字符为1)
此外对于字符串指针,则应该用 length()函数
string s[]={"abc","cd","ef"};
cout<<s[0].length()<<endl;
输出应为3;也就是abc的长度