1. 程式人生 > >百度面試題 字串中單詞的逆轉,即將單詞出現的順序進行逆轉

百度面試題 字串中單詞的逆轉,即將單詞出現的順序進行逆轉

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

void Rotate(char *start,char *end)
{
if(start == NULL || end == NULL) return ;
while(start<end)
{
char temp = *start;
*start = *end;
*end = temp;
--end;++start;
}
}

void RotateString(char *a,int n)
{
int i,j;
char *start =a;
char *end = a;
while(*start != '\0')
{
if(*start == ' ')
{
++start;++end;
continue;
}
else if(*end == ' ' || *end == '\0')
{
Rotate(start,--end);
start = ++end;
}
else
++end;
}
start = a;
Rotate(start,end-1);
printf("%s\n",a);
}

int main()
{
char a[] ="how are you";
printf("source string: %s\n",a);
RotateString(a,11);
return 0;

}

執行結果:

source string: how are you
you are how