C++ 字符串长度获取 sizeof、strlen、string.length、string.size
刚开始在获取字符数组和string字符串的长度的时候对函数的使用不是很清楚.
实践出真知
#include <iostream>
#include <typeinfo>
#include <string>
#include <cstring>
using namespace std;
int main()
{
char char1[] = {'a','b'};
char char2[9] = {'c','d','e','f'};
char* char3 = (char*)"hello world";
string char4 = "this is a string.";
cout<< "char1[10] = {'a','b'} -> sizeof:"<<sizeof(char1)<<endl;
cout<< "char2[9] = {'c','d','e','f'} -> sizeof:"<<sizeof(char2)<<endl;
cout<< "char3 \"hello world\" -> sizeof:"<<sizeof(char3)<<endl;
cout<< "char4 string \"this is a string.\"-> sizeof:"<<sizeof(char4)<<endl;
cout<<endl;
cout<< "char1[10] = {'a','b'} -> strlen:"<<strlen(char1)<<endl;
cout<< "char2[9] = {'c','d','e','f'} -> strlen:"<<strlen(char2)<<endl;
cout<< "char3 \"hello world\" -> strlen:"<<strlen(char3)<<endl;
// cout<< "char4 -> strlen:"<<strlen(char4)<<endl; //编译不通过
cout<<endl;
cout<< "char4 string \"this is a string.\"-> length:"<<char4.length()<<endl;
cout<< "char4 string \"this is a string.\"-> size:"<<char4.size()<<endl;
return 0;
}
结果:
F:\ClionProject\jianZhiOffer\cmake-build-debug\jianZhiOffer.exe
char1[10] = {'a','b'} -> sizeof:2
char2[9] = {'c','d','e','f'} -> sizeof:9
char3 "hello world" -> sizeof:8
char4 string "this is a string."-> sizeof:32
char1[10] = {'a','b'} -> strlen:2
char2[9] = {'c','d','e','f'} -> strlen:4
char3 "hello world" -> strlen:11
char4 string "this is a string."-> length:17
char4 string "this is a string."-> size:17
Process finished with exit code 0
对于字符数组:sizeof得到的是字符数组的容量,strlen是的到的字符的长度
对于字符指针:sizeof得到的是指针的字节数,strlen得到的是指针指向的字符的个数
对于string:sizeof得到的变量的字符大小,而length和size得到的是变量中字符串的长度。