用string的成员方法length()或者size()都可以取得字符串长度
#include
#include
using namespace std;
int main()
{
string str = "Test string";
cout << str.length() << endl;
cout << str.size() << endl;
return 0;
}
二者没有本质的区别,大部分情况都可以互换使用。但是表示的意义略有不同。
length()比较直观,表示的就是该字符串的长度。
size()表示的是string这个容器中的元素个数。如果使用过std::vector之类的容器的话,可以把string看做是一个vector
另外,strlen同样也可以用于C++的string。但是需要用c_str()将C++ string转换为char*类型。如下:
cout << strlen(str.c_str()) << endl;
但是不推荐这么做,有点画蛇添足的感觉
调用string对象的length()成员函数即可:
//---------------------------------------------------------------------------
#include
#include
int main(void)
{
std::string abc("abc");
std::cout<
}
//---------------------------------------------------------------------------
#include
#include
using namespace std;
void main()
{
string str;
str = "hello,world!";
len = str.length();
printf("%d",len);
}
你说的应该是C++的string类吧,你可以看看那个类的结构,
C++中已经封装了CString类型了。你只要直接使用相关的接口就可以了。
string s;
s.size()就可以得到字符创的长度了。