[1205 单词翻转] 解题报告

题目描写叙述 Description

给出一个英语句子,希望你把句子里的单词顺序都翻转过来

输入描写叙述 Input Description

输入包含一个英语句子。

输出描写叙述 Output Description

按单词的顺序把单词倒序输出

例子输入 Sample Input

I love you

例子输出 Sample Output

you love I

数据范围及提示 Data Size & Hint

简单的字符串操作

解题思路: 

步骤一:简单来讲能够使用两次翻转实现,第一次对总体做一个翻转,得到"ahah tneduts a ma I"

步骤二:然后对得到的字符串中的单词做一个翻转,得到"haha student a am I"

代码:

#include <stdio.h>
#include <string.h>

void Reverse(char*pbegin,char *pend){
    if(pbegin==NULL||pend==NULL)
        return;
    while(pbegin<pend)
    {
        char tmp;
        tmp=*pbegin;
        *pbegin=*pend;
        *pend=tmp;
        ++pbegin;
        --pend;
    }
}

int main()
{
    char str[100];
    char temp = NULL;
    int i = 0;
    while ((temp = getchar())!= '
') {
        str[i++] = temp;
    }
    str[i] = '';
    
    // 1.总体翻转"tnedutS a ma I"
    Reverse(str, str + strlen(str)-1);
    
    // 2.单词翻转"Student a am I"
    char *sentence = str;
    char *pWord = str;
    int wordLength = 0;
    while (*sentence != ''){         // sentence结束条件
        if (*pWord != ' ') {
            pWord++;
            wordLength++;
        }else{
            Reverse(pWord -wordLength, pWord - 1);     // 当*pWord == ' ',那么就进行单词翻转
            pWord++;
            wordLength = 0;
        }
        sentence++;
    }
    
    printf("%s
",str);
    return 0;
}


原文地址:https://www.cnblogs.com/slgkaifa/p/7209507.html