C++中STL学习

STL学习

String

string类的赋值

 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     string s1;//初始化字符串,空字符串
 9     string s2 = s1; //拷贝初始化,深拷贝字符串
10     string s3 = "I am Yasuo"; //直接初始化,s3存了字符串
11     string s4(10, 'a'); //s4存的字符串是aaaaaaaaaa
12     string s5(s4); //拷贝初始化,深拷贝字符串
13     string s6("I am Ali"); //直接初始化
14     string s7 = string(6, 'c'); //拷贝初始化,cccccc
15 
16     //string的各种操作
17     string s8 = s3 + s6;//将两个字符串合并成一个
18     s3 = s6;//用一个字符串来替代另一个字符串的对用元素
19 
20     cin >> s1;
21 
22     cout << s1 << endl;
23     cout << s2 << endl;
24     cout << s3 << endl;
25     cout << s4 << endl;
26     cout << s5 << endl;
27     cout << s6 << endl;
28     cout << s7 << endl;
29     cout << s8 << endl;
30     cout << "s7 size = " << s7.size() << endl; //字符串长度,不包括结束符
31     cout << (s2.empty() ? "This string is empty" : "This string is not empty") << endl;;
32 
33     system("pause");
34     return 0;
35 }

运行结果:

qwer
qwer

I am Ali
aaaaaaaaaa
aaaaaaaaaa
I am Ali
cccccc
I am YasuoI am Ali
s7 size = 6
This string is empty

 string的IO操作

使用cin读入字符串,遇到空白就停止读取。

“Hello World”

 如果需要将整个hello world读进去怎么办?

如果我们想把整个hello world读进来怎么办?那就这样做

cin>>s1>>s2;

hello存在s1里,world存在s2里了。

有时我们想把一个句子存下来,又不想像上面那样创建多个string来存储单词,怎么办?

那就是用getline来获取一整行内容。

string str;
getline(cin, str);
cout << str << endl;

把string对象和字符面值及字符串面值混在一条语句中使用时,必须确保+的两侧的运算对象至少有一个是string

string s1 = s2 + ", "; //正确
string s3 = "s " + ", "; //错误
string s4 = "hello" + ", " + s1; //错误

处理string中的字符

访问字符串的每个字符

for (int i = 0; i < s3.size(); i++)
{
    cout << s3[i] << endl;
    s3[i] = 's';
}

 

在C语言中我都是用下标或者指针来访问数组元素,而在C++里,有个新奇的东西叫做迭代器iterator,我们可以使用它来访问容器元素。

string str("hi sysu");
for (string::iterator it = str.begin(); it != str.end(); it++)
{
    cout << *it << endl;
}

我们也可以是使用const_iterator使得访问元素时是能读不能写,这跟常量指针意思差不多。

string str2("hi sysu");
for (string::const_iterator it = str2.begin(); it != str2.end(); it++)
{
    cout << *it << endl;
    *it = 'l'; //这是错误的,不能写
}

 

 

posted @ 2019-06-27 15:41  xjyxp01  阅读(192)  评论(0编辑  收藏  举报