c++string库的简单应用

1.string

string在c++中是标准库类型,表示可变长的字符序列。先来看一下初始化string对象的方法。

#include<string>
#include<iostream>
using namespace std;
void main()
{
	string s;//默认是一个空串
	string s1(s);//s1是s的副本
	string s2 = s1;
	string s3("hello");//利用字面值赋值,s3是“hello”的副本,不包含最后的空字符
	string s4 = "hello";
	string s5(10,'c');//初始化为10个c字符的串。

	system("system");
}

2.读写string对象

看下面的代码

#include<iostream>
#include<string>
using namespace std;
void main()
{
	string s("hello word");
	cout << s << endl;//必须包含头文件string才能输出
	string s2;
	cin >> s2;//读入string对象,不过注意cin只能读取到空白处停止
	getline(cin, s2);//利用getline读取一整行,包括空格

	system("pause");
}

3.string的empty和size操作

#include<iostream>
#include<string>
using namespace std;
void main()
{
	string s("hello word");
	cout << s.size() << endl;//size使用后返回s的字符数量。
	if (s.empty())//如果为空,那么返回一个真值
		cout << "1";
	else
		cout << "2";
	system("pause");
}

4.string::size_type

在c++中,该类型是由size()返回的数据类型,是string::size_type类型的,

通常我们不需要知道的这么清楚,所以可以使用auto或者decltype类型表示符。

5.比较string大小

看下面的代码

#include<iostream>
#include<string>
using namespace std;
void main()
{
	string s1("hello");
	string s2("helloword");
	string s3("helw");
	if (s2 > s1)
		cout << "1" << endl;//如果较少的string对象包含在较大的string对象里面,那么较大的string对象大
	if (s3 > s1)
		cout << "2" << endl;//如果不是包含关系,那么比较第一个不同的字符


	system("pause");
}

6.string的加法

string中的加法很好理解,就是把两个string对象加在一起,应该注意的是c++允许把string和c风格字符串相加,加

法结果是一个string对象。

猜你喜欢

转载自blog.csdn.net/qq_43702629/article/details/89026319