下面随笔给出c++ string类使用及用string类解决整行字符串输入。
string类
使用字符串类string表示字符串
string实际上是对字符数组操作的封装
string类常用的构造函数
string(); //默认构造函数,建立一个长度为0的串
例:
string s1;
string(const char *s); //用指针s所指向的字符串常量初始化string对象
例:
string s2 = “abc”;
string(const string& rhs); //复制构造函数
例:
string s3 = s2;
string类常用操作
s + t 将串s和t连接成一个新串
s = t 用t更新s
s == t 判断s与t是否相等
s != t 判断s与t是否不等
s < t 判断s是否小于t(按字典顺序比较)
s <= t 判断s是否小于或等于t (按字典顺序比较)
s > t 判断s是否大于t (按字典顺序比较)
s >= t 判断s是否大于或等于t (按字典顺序比较)
s[i] 访问串中下标为i的字符
例:
string s1 = "abc", s2 = "def";
string s3 = s1 + s2; //结果是"abcdef"
bool s4 = (s1 < s2); //结果是true
char s5 = s2[1]; //结果是'e'
1 //例 string类应用举例
2
3 #include <string>
4
5 #include <iostream>
6
7 using namespace std;
8
9 //根据value的值输出true或false
10
11 //title为提示文字
12
13 inline void test(const char *title, bool value)
14
15 {
16
17 cout << title << " returns "
18
19 << (value ? "true" : "false") << endl;
20
21 }
22
23 int main() {
24
25 string s1 = "DEF";
26
27 cout << "s1 is " << s1 << endl;
28
29 string s2;
30
31 cout << "Please enter s2: ";
32
33 cin >> s2;
34
35 cout << "length of s2: " << s2.length() << endl;
36
37 //比较运算符的测试
38
39 test("s1 <= \"ABC\"", s1 <= "ABC");
40
41 test("\"DEF\" <= s1", "DEF" <= s1);
42
43 //连接运算符的测试
44
45 s2 += s1;
46
47 cout << "s2 = s2 + s1: " << s2 << endl;
48
49 cout << "length of s2: " << s2.length() << endl;
50
51 return 0;
52
53 }
用string类解决输入整行字符串
用cin的>>操作符输入字符串,会以空格作为分隔符,空格后的内容会在下一回输入时被读取
输入整行字符串
getline可以输入整行字符串(要包string头文件),例如:
getline(cin, s2);
输入字符串时,可以使用其它分隔符作为字符串结束的标志(例如逗号、分号),将分隔符作为getline的第3个参数即可,例如:
getline(cin, s2, ',');
1 //例 用getline输入字符串
2
3 include <iostream>
4
5 #include <string>
6
7 using namespace std;
8
9 int main() {
10
11 for (int i = 0; i < 2; i++){
12
13 string city, state;
14
15 getline(cin, city, ',');
16
17 getline(cin, state);
18
19 cout << "City:" << city << “ State:" << state << endl;
20
21 }
22
23 return 0;
24
25 }
26
27 //运行结果:
28
29 Beijing,China
30
31 City: Beijing State: China
32
33 San Francisco,the United States
34
35 City: San Francisco State: the United States