题解报告: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代码:

 #include<bits/stdc++.h>
using namespace std;
char a[];
int main()
{
int T,len,x,y;
while(cin>>T){
getchar();//吃掉回车符
while(T--){
gets(a);
len=strlen(a);
for(int i=;i<len;++i){
x=i;//标记当前单词的起始坐标
while(a[i]!=' ' && a[i]!='\0')++i;//循环直到遇到空字符
y=i-;//标记单词尾坐标
for(int j=y;j>=x;--j)
printf("%c",a[j]);//反序输出
if(a[i]==' ')cout<<' ';//如果此时a[i]是空字符的话顺便输出
}
cout<<endl;//换行
}
}
return ;
}

AC代码二之C++代码:

 #include<bits/stdc++.h>
using namespace std;
int t;string str,tmp;size_t pos,pre;
int main(){
while(cin>>t){
getchar();
while(t--){
getline(cin,str);pre=pos=;//初始定位为0
while((pos=str.find(" ",pos))!=string::npos){
tmp=str.substr(pre,pos-pre);//每次从pos位置开始截取pos-pre个字符
reverse(tmp.begin(),tmp.end());//反转字符串
cout<<tmp<<' ';//输出并且带空格输出
pre=++pos;//pre指向下一个位置
}
tmp=str.substr(pre);//获取最后的一个单词
reverse(tmp.begin(),tmp.end());//反转字符串
cout<<tmp<<endl;//直接输出并且换行
}
}
return ;
}
上一篇:freeCodeCamp:Convert HTML Entities


下一篇:uva11401