标准库类型string
C++提供的抽象数据类型(ADT),用于进行字符串操作;
字符串是软件系统中最常见的数据结构之一;
string类的编写时常见的笔试题目
string类型支持可变长度的字符串
例如:
[hongfuhao@localhost string]$ vim main.cpp
13 #include <string>
14 #include <iostream>
15 using namespace std;
16
17 int main()
18 {
19 cout<<"hello string"<<endl;
20
21
22 string a;
23 cout<<a<<endl;
24
25 return 0;
26 }
27
编译运行:
[hongfuhao@localhost string]$ g++ main.cpp
[hongfuhao@localhost string]$ ./a.out
hello string
[hongfuhao@localhost string]$
字符串对象的初始化方法:
初始化方法 | 代码解释 |
string s1; | 默认构造函数,s1位空字符串 |
string s2(s1); | 将s2初始化为s1的一个副本 |
string s3(“value”); | 将s3初始化为字符串的副本 |
string s4(n,'c'); | 将字符串初始化为字符c的n个副本 |
第三行的初始化方法:
13 #include <string>
14 #include <iostream>
15 using namespace std;
16
17 int main()
18 {
19 cout<<"hello string"<<endl;
20
21
22 string a("C++");
23 cout<<a<<endl;
24
25 return 0;
26 }
27
编译运行:
[hongfuhao@localhost string]$ g++ main.cpp
[hongfuhao@localhost string]$ ./a.out
hello string
C++
[hongfuhao@localhost string]$
第四行初始化方法:
13 #include <string>
14 #include <iostream>
15 using namespace std;
16
17 int main()
18 {
19 cout<<"hello string"<<endl;
20
21
22 string a(5,'c');
23 cout<<a<<endl;
24
25 return 0;
26 }
27
编译运行:
[hongfuhao@localhost string]$ g++ main.cpp
[hongfuhao@localhost string]$ ./a.out
hello string
ccccc
[hongfuhao@localhost string]$
标准库提供的函数:
string操作 | 代码解释 |
s.empty() | 如果字符串为空,返回true,否则返回false |
s.size() | 返回字符串中字符的个数 |
s[n] | 返回字符串中第n个字符,下标从0开始 |
s1+s2 //C语言中strcat函数 | 将s1和s2连接为一个新的字符串,返回新生成的字符串 |
s1=s2 | 将s1的内容替换成s2的内容 |
v1==v2 //C语言中strcmp | 比较v1和v2的内容,相等则返回true,否则返回false |
!=,<,<=,>,>= | 保持这些操作符惯有的含义 |
13 #include <string>
14 #include <iostream>
15 using namespace std;
16
17 int main()
18 {
19 cout<<"hello string"<<endl;
20
21
22 // string a(5,'c');
23 // cout<<a<<endl;
24 string d("my name is hongfuhao");
25 cout<<"d:"<<d<<endl;
26 if(d.empty())
27 {
28 cout<<"The d is empty"<<endl;
29
30 }
31 else
32 {
33 cout<<"string's size is "<<d.size()<<endl;
34 }
35 return 0;
36 }
编译运行:
[hongfuhao@localhost string]$ g++ main.cpp
[hongfuhao@localhost string]$ ./a.out
hello string
d:my name is hongfuhao
string's size is 20
[hongfuhao@localhost string]$
看看另一个:
13 #include <string>
14 #include <iostream>
15 using namespace std;
16
17 int main()
18 {
19 cout<<"hello string"<<endl;
20
21
22 // string a(5,'c');
23 // cout<<a<<endl;
24 string d("my name is hongfuhao");
25 cout<<"d:"<<d<<endl;
26 if(d.empty())
27 {
28 cout<<"The d is empty"<<endl;
29
30 }
31 else
32 {
33 cout<<"string's size is "<<d.size()<<endl;
34 }
35
36 string b("hong");
37 string c("fuhao");
38 string e=b+c;
39 if(e==d)
40 {
41 cout<<"e equals d"<<endl;
42 }
43 else
44 {
45 cout<<"e doesn't equal d"<<endl;
46 }
47 return 0;
48 }
编译运行:
[hongfuhao@localhost string]$ g++ main.cpp
[hongfuhao@localhost string]$ ./a.out
hello string
d:my name is hongfuhao
string's size is 20
e doesn't equal d
对象的名称命名在实际工作中要命名有意义的名字,不能像本文中简单的abcd,本文只是用来简单测试代码。