C++中求string类型字符串的长度的方法

在代码中经常会求字符串的有效长度,对char型字符串数组大家会用strlen来求它的有效长度,如何求string类型字符串的有效长度呢?这里有三种方法。

(1)使用string的成员函数length();

这里获取的即为字符串的有效长度。

#define _CRT_SECURE_NO_WARNINGS
#include "iostream"
#include "string"
using namespace std;

int main()
{
	string str = "hello world";
	int len = str.length();

	cout<<len<<endl;
	system("pause");	
	return 0;
}	

(2)使用string的成员函数size();

这里size()表示string容器中有效元素的个数。以达到获取字符串长度的目的。

#define _CRT_SECURE_NO_WARNINGS
#include "iostream"
#include "string"
using namespace std;

int main()
{
	string str = "hello world";
	int len = str.size();

	cout<<len<<endl;
	system("pause");	
	return 0;
}	

(3)使用strlen函数;

不能直接使用strlen函数来获取有效长度,需要先将string转换为char*类型,这里需要用到c_str()函数。

#define _CRT_SECURE_NO_WARNINGS
#include "iostream"
#include "string"
using namespace std;

int main()
{
	string str = "hello world";
	int len = strlen(str.c_str());

	cout<<len<<endl;
	system("pause");	
	return 0;
}	
发布了36 篇原创文章 · 获赞 6 · 访问量 2042

猜你喜欢

转载自blog.csdn.net/the_sea1/article/details/102549069