HDU 1062 Text Reverse

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

题意:转置一个字符串内的所有单词。

解法:读取‘ ’或‘’作为一个单词结束的标记,可用头文件<string.h>里的strrev函数转置单词,比较方便。也可以采用字符压栈的方法来转置单词(利用堆栈的先进后出性质)。或者用最传统的方法,数组存放字符,然后转置。

AC:

//用strrev函数实现,需要注意的是,部分编译器不支持非标准库函数strrev。

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
    int n,l,j;
    cin >> n;
    getchar();
    while(n--)
    {
        char p[1010],temp[1010];
        gets(p);
        l = strlen(p),j=0;
        for(int i = 0 ; i <= l ;i ++)
        {
            if(p[i] == ' ' || p[i] == '')
            {
                j = 0;
                strrev(temp);
                if(p[i] == ' ')
                    cout << temp << ' ';
                else cout <<temp;
                temp[0] = '';
            }
            else
                {
                    temp[j++] = p[i];
                    temp[j] = '';
                }
        }
        cout <<endl;
    }
    return 0;
}

//用堆栈的方法实现。

#include<stdio.h>
#include<stack>
using namespace std;
int main()
{
 int n;
    char ch;
 scanf("%d",&n);
 getchar(); /*吸收回车符*/
 while(n--)
 {
  stack<char> s; /*定义栈*/
  while(true)
  {
   ch=getchar(); /*压栈时,一次压入一个字符*/
            if(ch==' '||ch=='
'||ch==EOF)
   {
    while(!s.empty())
    {
     printf("%c",s.top()); 
     s.pop(); /*清除栈顶元素*/
    }
    if(ch=='
'||ch==EOF)  
     break;  /*绝对不能少,控制输出结束*/
    printf(" ");
   }
   else
    s.push(ch);
  }
  printf("
");
 }
 return 0;
}

//用数组的方法实现

#include<stdio.h>
#include<string.h>
int main()
{
    int i,n,len,j,k,t;
    char s1[1005],s2[100];
    scanf("%d",&n);
    getchar();
    while(n--)
    {
        gets(s1);
        len=strlen(s1);
        for(i=0,j=0,t=0;i<len;i++)
        {
            if(s1[i]!=' ')
                s2[j++]=s1[i]; /*保存单词*/
            else
            {
                if(t>0) printf(" "); /*控制格式*/
                for(k=j-1;k>=0;k--) 
                    printf("%c",s2[k]); /*反转输出*/
                j=0;
                t++;
            }
            if(i==len-1) /*反转最后一个单词,这里要特别注意*/
            {
                printf(" ");
                for(k=j-1;k>=0;k--)
                    printf("%c",s2[k]);
            }
        }
        printf("
");
    }
    return 0;
}

需要注意:

strlen不计算字符串结尾的‘’ 

用getchar()读取t后的一个回车,避免编译器认为回车为第一个字符串.

temp字符串重新定义后加上''.

原文地址:https://www.cnblogs.com/zz990728/p/8881797.html