C/C++编程学习 - 第18周 ⑦ 单词倒排

题目链接

题目描述

编写程序,读入一行英文(只包含字母和空格,单词间以单个空格分隔),将所有单词的顺序倒排并输出,依然以单个空格分隔。

输入格式
输入为一个字符串(字符串长度至多为 100)。

输出格式
输出为按要求排序后的字符串。

Sample Input

I am a student

Sample Output

student a am I

思路

题意就是,读入单词,反向输出。

C++代码1:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    string str, temp = "";
    stack<string> s;
    getline(cin, str);
    int len = str.length();
    for(int i = 0; i < len; i++)
    {
        if((str[i] <= 'z' && str[i] >= 'a') || (str[i] <= 'Z' && str[i] >= 'A'))
        {
            temp += str[i];
            while((str[i + 1] <= 'z' && str[i + 1] >= 'a') || (str[i + 1] <= 'Z' && str[i + 1] >= 'A'))
            {
            	temp += str[i + 1];
				i++;
			}
            s.push(temp);
            temp = "";
        }
    }
    while(!s.empty())
    {
        cout << s.top();
        s.pop();
        if(!s.empty()) cout<<" ";
    }
    return 0;
}

C++代码2:

#include<iostream>
using namespace std;
const int N = 1e5;
string a[N];
int main()
{
	int len = 0;
	while(cin >> a[len])
		len++;
	cout << a[len - 1];
	for(int i = len - 2;i >= 0; i--)
		cout <<" " << a[i];
	return 0;
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水蛙菌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值