C 艹 字符串问题求解

2014-10-21 11:32:56 +08:00
 spencerqiu
题目描述 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 }
2309 次点击
所在节点    问与答
5 条回复
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, " "));
Exin
2014-10-21 12:04:21 +08:00
这个是用到了栈(Stack)的概念
可以弄一个String的数组,从0位置(底部)开始遇到空格就保存一个单词
然后到句末就从String数组顶部逐个输出,最后加不加空格看具体题目的情况而定
jakwings
2014-10-21 12:45:39 +08:00
提供一种面对对象的方法:
https://gist.github.com/jakwings/4f9d16b4e32c953ba8e1
TMBest
2014-10-21 12:55:03 +08:00
1,先将整个字符串翻转
2,将每个单词翻转
jakwings
2014-10-21 12:59:03 +08:00
@jakwings 哎,我顺序弄错了,回去面壁。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/140456

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX