string类型
(1).用string的成员方法length()获取字符串长度
length()比较直观,表示的就是该字符串的长度。
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s;
cin>>s;
cout<<s.length()<<endl;
return 0;
}
(2).用string的成员方法size()获取字符串长度
size()表示的是string这个容器中的元素个数。如果使用过std::vector之类的容器的话,可以把string看做是一个vector<char> (这里只是举例,并不能等价), char就是这个容器的元素类型。那么size()表示的就是这个vector(容器)中char的个数。
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s;
cin>>s;
cout<<s.size()<<endl;
return 0;
}
(3).用strlen获取字符串长度
strlen同样也可以用于C++的string。但是需要用c_str()将C++ string转换为char*类型。
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s;
cin>>s;
int len=s.length();
cout<<len<<endl;
return 0;
}
char类型
(1).用strlen函数
strlen()函数求出的字符串长度为有效长度,既不包含字符串末尾结束符 ‘\0’;
#include <bits/stdc++.h>
using namespace std;
int main()
{
char s[100];
cin>>s;
cout<<strlen(s)<<endl;
return 0;
}
(2).用sizeof函数
sizeof()操作符求出的长度包含字符串末尾的结束符 ‘\0’;
#include <bits/stdc++.h>
using namespace std;
int main()
{
char s[100];
cin>>s;
cout<<sizeof(s)<<endl;
return 0;
}
注意:当在函数内部使用sizeof()求解由函数的形参传入的字符数组的长度时,得到的结果为指针的长度,既对应变量的字节数,而不是字符串的长度,此处一定要小心。
(3).
#include <bits/stdc++.h>
using namespace std;
int main()
{
char s[100];
cin>>s;
int i=0;
while(s[i++]!='\0');
cout<<i<<endl;
return 0;
}