Text Reverse
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 35567 Accepted Submission(s): 13963
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.
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.HintRemember to use getchar() to read '\n' after the interger T, then you may use gets() to read a line and process it.
【分析】串逆序+单词处理
题意:读入T行 每行长度不超过1000且含有空格的文本,找出其中的单词并逆序处理。
问题实质即找到每个单词的左右端点,然后对子串str[左端点...右端点]逆序处理即可。注意getchar()和gets(str)函数的使用。
#include <stdio.h>
#include <string.h>
#define maxlen 1010
int T;
char str[maxlen];
void Reverse(char *s,int l,int r) //子串str[l...r]逆序
{
int i;
char temp;
while(l<=r)
{
temp=s[l];
s[l]=s[r];
s[r]=temp;
l++,r--;
}
}
int main()
{
int i,j;
int len,left,right; //串长度.单词左右端点
while(scanf("%d",&T)!=EOF)
{
//将输入T之后的回车"吸收"掉,避免影响后续输入
getchar();
for(i=0;i<T;i++)
{
//读入含空格的串
gets(str);
j=0,len=strlen(str);
//初始化单词左右端点均为0
left=right=0;
while(j<len)
{
//遇到空格,空格前一个字符为单词的右端点
if(str[j]==' ')
{
right=j-1;
//逆序
Reverse(str,left,right);
//遇到多个空格相连的情况,跳过
while(str[++j]==' ');
//确定下一个单词的左端点
left=j;
}
//当前考察的字符是串的最后一个字符,且不是空格,则右端点为len-1
else if(str[j]!=' ' && j==len-1)
{
right=j;
//逆序
Reverse(str,left,right);
}
//继续考察当前字符后面的一个字符
j++;
}
printf("%s\n",str);
}
}
return 0;
}