PAT 乙级 1009

题目

    题目地址:PAT 乙级 1009

 

题解

    本题本身属于比较简单的字符串操作题,但是因为对于string的操作和函数不熟悉导致本题做起来很费劲,需要加强对于string类以及相关方法的理解和熟练程度。

    1. string读取字符串时,默认以空格或者回车作为结束输入的标志,所以在本题中,如果用string的普通输入无法完整读入数据,因此需要使用getline方法

          getline()

                头文件:#include <string>

                函数原型:getline(istream &is,string &str,char delim)

                主要功能:读入整行数据,不把空格作为判断输入结束的条件,默认是回车,可以自行设置结束条件

                istream &is表示一个输入流,譬如cin,string表示把从输入流读入的字符串存放在这个字符串中(&str其实就是一个变量),char delim是终止符(默认为回车,还可以是别的符号,如#,*之类的都可以)

    2. 如果需要对某一个字符串进行切片处理时,本题中用到的方法是substr()

          substr()

               头文件:#include <string>

               函数原型:substr(size_t pos = 0, size_t len = npos)

               主要功能:复制某一范围内的子字符串,要求从指定位置开始,并具有指定的长度

 

代码

 1 #include <iostream>
 2 #include <string>
 3 #include <vector>
 4 using namespace std;
 5 
 6 int main() {
 7     string str;
 8     vector<string> out_str;
 9     getline(cin, str);
10     str[str.size()] = ' ';
11     int start = 0, cnt = 0;
12     string tmp;
13     for (int i = 0; i < (str.size() + 1); i++) {
14         if (str[i] == ' ') {
15             tmp = str.substr(start, cnt);
16             out_str.push_back(tmp);
17             start = i + 1;
18             cnt = -1;
19         }
20         cnt++;
21     }
22     for (int i = out_str.size() - 1; i >= 0; i--) {
23         cout << out_str[i];
24         if (i != 0)
25             cout << ' ';
26     }
27 
28     return 0;
29 }

 

更新后的代码

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 
 5 int main() {
 6     string str;
 7     getline(cin, str);
 8     int last = str.size();
 9     for (int i = str.size() - 1; i >= 0; i--) {
10         if (str[i] == ' ' || i == 0) {
11             if (i == 0) i = -1;
12             for (int j = i + 1; j < last; j++)
13                 cout << str[j];
14             if (i != -1)
15                 cout << ' ';
16             else
17                 cout << endl;
18             last = i;
19         }
20     }
21 
22     return 0;
23 }

 

posted @ 2018-07-18 00:44  moujun  阅读(299)  评论(0编辑  收藏  举报