下面是代码,请大神看看,方法是先把每个翻转再将整句句子翻转。
输入的是the sky is blue,应该出来的是blue is the sky,但现在出来的是elub is the sky
#include
#include
void Reverse(char* str)
{
char *p;
char *start,*end;//单词头尾指针
char temp;
int flag=0;//如果p指向符号为1
start=p=str;//头指针指向数组首地址,p也从首地址开始遍历
while(*p!='\0')
{
if(*p==' ')//识别单词,flag值为1
{
flag=1;
end=p-1;//p识别到了符号,因此flag=1。end即指向p-1.
while(start<end)
{
temp=*start;
*start=*end;
*end=temp;
start++;
end--;
}///将一个单词的字母顺序逆转。
}
if(flag==1)
{
start=p+1;
flag=0;//到下一个单词
}
p=p+1;
}
start=str;
end=p-1;
while(start<end)//整句话逆序
{
temp=*start;
*start=*end;
*end=temp;
start++;
end--;
}
return;
}
int main()
{
char a[]="the sky is blue";
printf("%s\n",a);
Reverse(a);
printf("%s\n",a);
return 0;
}