Text Reverse 杭电1062

本文介绍了一种编程挑战,要求将给定的字符串中的单词逆序输出。提供了两种不同的实现方式,一种使用C语言通过字符串处理完成,另一种则采用C++结合栈的数据结构实现。

Problem Description

Ignatius likes to write words in reverse way. Given a single line of text which is written by Ignatius, you should reverse all the words and then output them.

 

 

Input

The input contains several test cases. The first line of the input is a single integer T which is the number of test cases. T test cases follow.
Each test case contains a single line with several words. There will be at most 1000 characters in a line.

 

 

Output

For each test case, you should output the text which is processed.

 

 

Sample Input


 

3

olleh !dlrow

m'I morf .udh

I ekil .mca

 

 

Sample Output


 

hello world!

I'm from hdu.

I like acm.

 #include<stdio.h>//在做的时候没有考虑到 最后一个单词后面没有空格
#include<string.h>
char s[1002];
int main() {
    int test,i,j,len,k;
    scanf("%d",&test);
    getchar();
    while(test--) {
        gets(s);
        len=strlen(s);
        for(i=0,k=0; i<len; i++) {
            if(s[i]==' ') {
                for(j=i-1; j>=k; j--) {
                    printf("%c",s[j]);
                }
                printf(" ");
                k=i+1;
            }
        }
        for(j=len-1; j>=k; j--)
            printf("%c",s[j]);
        printf("\n");
    }
    return 0;
}

 #include <iostream>
#include <stack>
#include <stdio.h>
using namespace std;
int main() {
    int n;
    cin>>n;
    getchar();  //因为下面要读一字符 需要消除换行符的影响
    char ch;
    while(n--) {
        //string temp;
        //getline(cin,temp);
        stack<char> s1;  //利用栈的特性 先进后出
        while(1) {
            ch = getchar();
            if(ch==' '||ch=='\n'||ch==EOF) { //如果遇到空字符(一个单词) 或换行符 (一行的结束) 或输入结束 即打印出栈的内容
                while(!s1.empty()) {
                    cout<<s1.top();
                    s1.pop();
                }
                if(ch=='\n'||ch==EOF) { //一定要有 判断是不是输入结束
                    break;
                }
                cout<<" ";
            } else {
                s1.push(ch);  //否则的话 就不断进行压栈操作
            }
        }
        cout<<endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值