chapter2 string字符串处理

1、编写一段程序,使用范围for语句将字符串内的所有字符用X代替。

 1 #include<iostream>
 2 using namespace std;
 3 int main()
 4 {
 5     string s = "Hello World";
 6     for(auto &i:s)
 7     {
 8         i = 'X';
 9     }
10     cout << s << endl;
11     return 0;
12 }

 

2、就上一题完成的程序而言,如果将循环控制的变量类型设为Char将发生什么?先估计一下结果,然后完成编程进行验证。

 1 #include<iostream>
 2 using namespace std;
 3 int main()
 4 {
 5     string s = "Hello World";
 6     for(char &i:s)
 7     {
 8         i = 'X';
 9     }
10     cout << s << endl;
11     return 0;
12 }

合法,可以执行

 

3、分别用while循环和传统的for循环重写第一题的程序,你觉得哪种形式更好呢,为什么?

 1 #include<iostream>
 2 using namespace std;
 3 int main()
 4 {
 5     string s = "Hello World";
 6     /*
 7     for(decltype(s.size()) index = 0; index < s.size(); index++)
 8     {
 9         s[index] = 'X';
10     }
11     */
12     decltype(s.size()) index = 0;
13     while(index != s.size())
14     {
15         s[index] = 'X';
16         index++;
17     }
18     cout << s << endl;
19     return 0;
20 }

 

4、下面的程序有何作用?它合法吗?如果不合法,为什么?

string s;

cout << s[0] << endl;

合法,输出空串。

 

5、编写一段程序,读入一个包含标点符号的字符串,将标点符号去除后输出字符串剩下的部分。

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 int main()
 5 {
 6     char s;
 7     string result;
 8     while(cin >> s)
 9     {
10         if(!ispunct(s))
11             result += s;
12     }
13     cout << result << endl;
14     return 0;
15 }

 

6、下面的范围for语句合法吗?如果合法,c的类型是什么?

const string s = "Keep out!";

for(auto &c : s) { /*.....*/ }

合法,const char类型

posted @ 2018-03-24 22:39  抹茶奶绿不加冰  阅读(208)  评论(0编辑  收藏  举报