题目描述:
编写函数,输入一个英文的句子,翻转句子中单词的顺序。要求单词内字符的顺序不变,单词间空格符数量不变。
例如:"I am a student."反转成"student. a am I"。
翻转思路:
先翻转每个单词,然后再翻转整个句子。如先将“I am a student.”反转为“I ma a .tneduts”,然后再对中间结果“I ma a .tneduts”整体翻转,即为 “student. a am I”。
C代码实现
#include <stdio.h>
#include <string.h>
//反转一个单词[from,to]区间内的字母
void reserveString(char arr[],int from, int to)
{
while(from < to)
{
char tmp = arr[from];
arr[from]= arr[to];
arr[to] = tmp;
from ++;
to --;
}
}
//反转一句话,以'\0'结尾
void reserve(char ch[], int len)
{
int i=0;
int from = 0;
int to = 0;
while(i<=len)//数组中每个字符都要判定,包括'\0'
{
if(ch[to] == ' ' || ch[to]=='\0')
{
reserveString(ch, from,to-1); //先反转每个单词,[from,to-1]
from = ++to; //寻找下一个单词。
}
else
{
to++;
}
i++;
}
reserveString(ch, 0,len-1); //再整体反转
}
int main()
{
char ch[] = "i am a student.";
printf("%s\n",ch);
reserve(ch, strlen(ch));
printf("%s\n",ch);
return 0;
}
运行结果如下: