(1). 用string的成员方法length()获取字符串长度
length()比较直观,表示的就是该字符串的长度。
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str="hello world";
cout<< str.length() <<endl; //输出 11
return 0;
}
(2).用string的成员方法size()获取字符串长度
size()表示的是string这个容器中的元素个数。如果使用过std::vector之类的容器的话,可以把string看做是一个vector<char> (这里只是举例,并不能等价), char就是这个容器的元素类型。那么size()表示的就是这个vector(容器)中char的个数。
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str="hello world";
cout<< str.size() <<endl; //输出 11
return 0;
}
(3).用strlen获取字符串长度
strlen同样也可以用于C++的string。但是需要用c_str()将C++ string转换为char*类型。
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
string str="hello world";
cout<< strlen(str.c_str()) <<endl; 输出 11
return 0;
}