描述:给定一句英语,要求你编写程序,将句中所有单词的顺序颠倒输出。
输入:测试输入包含一个测试用例,在一行内给出总长度不超过80的字符串。字符串由若干单词和若干空格组成,其中单词是由英文字母(大小写有区分)组成的字符串,单词之间用1个空格分开,输入保证句子末尾没有多余的空格。
输出:每个测试用例的输出占一行,输出倒序后的句子。
inout:Hello World Here I Come
output:Come I Here World Hello
就是要熟练使用string里的函数
1 #include<iostream>
2 #include<string>
3 using namespace std;
4
5 int main()
6 {
7 string a, b,c;
8 getline(cin, a);
9 for (int i = 0; i < a.size(); i++)
10 {
11 if (a[i] == ' ')
12 {
13 c.push_back(' ');
14 b.insert(0, c); //字符串插入函数
15 c.erase(0); //删除函数
16 continue;
17 }
18 c.push_back(a[i]);
19 }
20 c.push_back(' ');
21 b.insert(0, c);
22 b.erase(b.size() - 1);
23 cout << b << endl;
24 system("pause");
25 return 0;
26 }
还有一种方法是把每个单词当成一个字符串,存在字符串数组了,逆序输出
1 #include<iostream>
2 #include<string>
3 using namespace std;
4
5 int main()
6 {
7 string a[100];
8 int count = 0;
9 do
10 {
11 cin >> a[count];
12 count++;
13 } while (getchar() != '\n');
14 for (int i = count - 1; i > 0; i--)
15 cout << a[i] << " ";
16 cout << a[0] << endl;
17 system("pause");
18 return 0;
19 }
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有