题目描述 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())!= '\n') {
str[i++] = temp;
}
str[i] = '\0';
// 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 != '\0'){ // sentence结束条件
if (*pWord != ' ') {
pWord++;
wordLength++;
}else{
Reverse(pWord -wordLength, pWord - 1); // 当*pWord == ' ',那么就进行单词翻转
pWord++;
wordLength = 0;
}
sentence++;
}
printf("%s\n",str);
return 0;
}