HDOJ1062. Text Reverse(串逆序+单词处理)

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.
 

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.

【分析】串逆序+单词处理

        题意:读入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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值