2014北大软工夏令营机试 C:单词翻转

本文介绍了使用C语言实现将句子中每个单词进行翻转的方法,包括两种参考代码,适用于初学者快速理解并实践字符串操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

2014软件工程夏令营上机考试 C:单词翻转


总时间限制: 
1000ms 
内存限制: 
65536kB
描述

输入一个句子(一行),将句子中的每一个单词翻转后输出

输入
只有一行,为一个字符串,不超过500个字符。单词之间以空格隔开。
输出
翻转每一个单词后的字符串
样例输入
hello world
样例输出
olleh dlrow

参考代码(1):
#include <iostream>
#include <stack>
#include <cstdio>
#include <cstring>
using namespace std;
int main(){
	char s[501];
	gets(s);
	stack<char>p;
	int i = -1;
	while(++i < strlen(s)){
        if(s[i]!=' '){
		   p.push(s[i]);
	    }else {
			while(!p.empty()){
				cout<<p.top();
				p.pop();

			}
			cout<<" ";
		}
	}
	while(!p.empty()){
        cout << p.top();
        p.pop();

    }
    cout << endl;
	return 0;
}

参考代码(2):
#include<iostream>
#include<stack>
#include<cstdio>
using namespace std;
int main(){
	char s[501];
	gets(s);
	stack<char>p;
	int i=0;
	while(true){
		
		if(s[i]=='\0'){
		   	while(!p.empty()){
				cout<<p.top();
				p.pop();
				
			}
		   break;
        }if(s[i]!=' '){
		   p.push(s[i]);
		   i++;
	    }
		else {
			while(!p.empty()){
				cout<<p.top();
				p.pop();
				
			}
			cout<<" ";
			i++;
		}
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值