码迷,mamicode.com
首页 > 编程语言 > 详细

HDU 1062.Text Reverse【栈或数组或字符串流】【字符处理】【8月30】

时间:2015-08-30 15:56:57      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:字符串处理   c++   acm   hdu   

Text Reverse

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.
Hint
Remember to use getchar() to read ‘\n‘ after the interger T, then you may use gets() to read a line and process it.
这个题可以用数组,也可以用栈,还可以用C字符串流来做。要注意,中间可能不止1个空格。坑!注意特殊的就可以了。用栈代码如下:

#include<cstdio>
#include<stack>
#include<cstring>
using namespace std;
int main(){
    int t;
    scanf("%d",&t);
    getchar();//吸收回车
    while(t--){
        char x;
        stack<char>f;
        while(1){
            x=getchar();
            if(x!=' '&&x!='\n'&&x!=EOF) f.push(x);
            else{
                while(!f.empty()){
                    printf("%c",f.top());
                    f.pop();
                }
                if(x=='\n'||x==EOF) break;
                printf(" ");
            }
        }
        printf("\n");
    }
    return 0;
}
技术分享

用C字符串流代码如下:

#include<cstdio>
#include<sstream>
#include<iostream>
using namespace std;
int main(){
    int T;
    string s,ss;
    scanf("%d",&T);
    getchar();
    while(T--){
        getline(cin,s);
        int x=0;
        while(s[x]==' '){//开头可能有空格
            printf(" ");
            x++;
        }
        istringstream sin(s);
        while(sin>>ss){
            x+=ss.length();
            for(int i=ss.length()-1;i>-1;i--)
                printf("%c",ss[i]);
            while(x<s.length()&&s[x]==' '){//中间空格可能不是一个
                printf(" ");
                x++;
            }
        }
        printf("\n");
    }
    return 0;
}
技术分享

版权声明:本文为博主原创文章,未经博主允许不得转载。

HDU 1062.Text Reverse【栈或数组或字符串流】【字符处理】【8月30】

标签:字符串处理   c++   acm   hdu   

原文地址:http://blog.csdn.net/a995549572/article/details/48104701

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!