杭电oj 1062 Text Reverse

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 Input3
olleh !dlrow
m’I morf .udh
I ekil .mca
Sample Outputhello 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.

Author Ignatius.L

题目翻译:
伊格纳修斯喜欢用相反的方式写单词。给定一行由Ignatius编写的文本,您应该反转所有单词,然后输出它们。

思路:
一道字符串的题。这就是所谓的水题吧,这种题要注意细节问题。
就是将一个字符串里面的连续的英文看做一个单词,将单词逆序,其他空格照常输出。
这里需要注意几个问题:
1、如果开头是空格,要将开头的空格照常输出
2、如果结尾有空格,结尾的空格也要照常输出。
3、标点符号看做单词里面的,不用特殊对待。

所以有这几种情况需要输出:
1、遇到空格(包括了最后一个字符是空格)
2、指针指向最后一个不是空格的字符

这里我使用的head和tail将单词的开头和结尾的位置记下来,其他涉及到空格的话就用while进行输出一直遇到不是空格就行(注意输出空格的时候不要越界,要在字符串的长度之内)。
注意小细节:
如果最后一个字符不是空格,是一个单独的单词的话,while循环输出空格后,指针就会指向一个不是空格的字符。退出while循环之后会在for循环中再将指针置加一次,如果指针退出while循环之后变为为了len-1(指向最后一个字符的话),那for循环的再置加就会越界,不会进行判断输出等操作了,所以我们可以在退出while循环之后将指针往后退一个,反正for循环会置加回来。(具体可以看下面代码注释)

题目代码:

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
//注意 用while循环的时候 j++之后 最后要减一下,要不然当最后一个字符是一个单词的时候不得行 
int main()
{
 char s[2000];
 int t;
 cin>>t;
 getchar();
 int head,tail;
 int k;
 for(int i=1;i<=t;i++)
 {
  k=0;
  gets(s);
  int len=strlen(s);
  while(s[k]==' '&&k<len)
  {
   printf(" ");
   k++;
  }
  head=k;//确定第一个开始单词的开始位置 
  for(int j=k;j<len;j++)
  {
   if(s[j]==' ')//读到空格的话 
   {
    tail=j-1;
    for(int p=tail;p>=head;p--)
    {
     printf("%c",s[p]);
    }
    while(s[j]==' '&&j<len)//处理空格 
    {
     printf(" ");
     j++;
    }
    head=j;
    j--;//因为for循环一会还要加一下,所以先减回来 
   }
   else if(j==len-1)//如果最后一个不是空格
   {
    tail=j; 
    for(int p=tail;p>=head;p--)
    {
     printf("%c",s[p]);
    }
   } 
  }
  cout<<endl;
 }
 
 return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值