这是一个创建于 3633 天前的主题,其中的信息可能已经有所发展或是发生改变。
题目描述 Description
给出一个英语句子,希望你把句子里的单词顺序都翻转过来
输入描述 Input Description
输入包括一个英语句子。
输出描述 Output Description
按单词的顺序把单词倒序输出
样例输入 Sample Input
I love you
样例输出 Sample Output
you love I
我的思路:
因为以空格隔开,我就在每看到一个空格就记录一次数据,输出,然后把计数器清零,但是似乎跑下来不太对。
代码:
01 #include<iostream>
02 #include<cstring>
03 #include<cstdlib>
04 using namespace std;
05 int main()
06 {
07 string s;
08 getline(cin,s);
09 int n=s.length();
10 int count=0;
11 string tmp;
12 for (int i=n-1;i>=0;i--)
13 {
14 if (s[i]==' ')
15 {
16 for (int i=count-2;i>=0;i--)
17 cout <<tmp[i];
18 cout <<" ";
19 count=0;
20 continue;
21 }
22 else
23 {
24 tmp[count]=s[i];
25 cout <<tmp[count];
26 count++;
27 }
28 }
29 system("pause");
30 return 0;
31 }
5 条回复 • 2014-10-21 12:59:03 +08:00
|
|
1
timonwong 2014-10-21 11:50:12 +08:00
方法很多种
vector<string> words{istream_iterator<string>{istringstream(s)}, istream_iterator<string>{}};
reverse_copy(words.begin(), words.end(), ostream_iterator<string>(cout, " "));
|
|
|
2
Exin 2014-10-21 12:04:21 +08:00
这个是用到了栈(Stack)的概念 可以弄一个String的数组,从0位置(底部)开始遇到空格就保存一个单词 然后到句末就从String数组顶部逐个输出,最后加不加空格看具体题目的情况而定
|
|
|
4
TMBest 2014-10-21 12:55:03 +08:00 via Android 1
1,先将整个字符串翻转 2,将每个单词翻转
|