题解报告:hdu 1062 Text Reverse

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1062

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.

解题思路:问题求解的是每个句子中每个单词的反转。

AC代码一之C代码:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 char a[1005];
 4 int main()
 5 {
 6     int T,len,x,y;
 7     while(cin>>T){
 8         getchar();//吃掉回车符
 9         while(T--){
10             gets(a);
11             len=strlen(a);
12             for(int i=0;i<len;++i){
13                 x=i;//标记当前单词的起始坐标
14                 while(a[i]!=' ' && a[i]!='')++i;//循环直到遇到空字符
15                 y=i-1;//标记单词尾坐标
16                 for(int j=y;j>=x;--j)
17                     printf("%c",a[j]);//反序输出
18                 if(a[i]==' ')cout<<' ';//如果此时a[i]是空字符的话顺便输出
19             }
20             cout<<endl;//换行
21         }
22     }
23     return 0;
24 }

 AC代码二之C++代码:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int t;string str,tmp;size_t pos,pre;
 4 int main(){
 5     while(cin>>t){
 6         getchar();
 7         while(t--){
 8             getline(cin,str);pre=pos=0;//初始定位为0
 9             while((pos=str.find(" ",pos))!=string::npos){
10                 tmp=str.substr(pre,pos-pre);//每次从pos位置开始截取pos-pre个字符
11                 reverse(tmp.begin(),tmp.end());//反转字符串
12                 cout<<tmp<<' ';//输出并且带空格输出
13                 pre=++pos;//pre指向下一个位置
14             }
15             tmp=str.substr(pre);//获取最后的一个单词
16             reverse(tmp.begin(),tmp.end());//反转字符串
17             cout<<tmp<<endl;//直接输出并且换行
18         }
19     }
20     return 0;
21 }
原文地址:https://www.cnblogs.com/acgoto/p/8635407.html