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

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;
}


你可能感兴趣的:(C++,ACM,字符串处理,HDU)