程序员算法之翻转单词中的字符

View Code
 1 #include <stdlib.h>

 2 #include <string.h>

 3 #include <stdio.h>

 4 void Reverse(char *pbegin,char *pend)

 5 {

 6     char temp;

 7     while(pbegin < pend)

 8     {

 9         temp = *pbegin;

10         *pbegin = *pend;

11         *pend = temp;

12         pbegin++;

13         pend--;

14     }

15 }

16 

17 void ReverseSentence(char *str)

18 {

19     char *pbegin = str;

20     char *pend = str + strlen(str) -1;

21     Reverse(pbegin,pend);

22     char *temp = str;

23     while(*temp != '\0')

24     {

25         if(*temp == ' ') 

26         {

27             Reverse(pbegin,temp - 1);

28             pbegin = temp + 1;

29         }

30         temp++;

31     }

32     Reverse(pbegin,temp - 1);

33 

34 }

35 

36 int main()

37 {

38     char str[] = "I am  a student.";

39     ReverseSentence(str);

40     printf("%s\n",str);

41     return 0;

42 }

 

你可能感兴趣的:(程序员)