把字符串中的字符反向排列

编写函数reverse_string,它的原型如下:

  void reverse_string( char *string );

函数把参数字符串中的字符反向排列。请使用指针而不是数组下标,不要使用任何C函数库中用于操作字符串的函数。

提示:不需要声明一个局部数组来临时存储参数字符串。

 1 #include <stdio.h>
 2 
 3 /*
 4 ** 将字符串的字符反向排列
 5 ** 不使用数组下标
 6 ** 不使用字符操作库函数
 7 ** 不用新的数组临时存储参数
 8 */
 9 void 
10 reverse_string( char *string )
11 {
12     char *s_head = string; // s_head指向第一个字符
13     char *s_end = string; 
14     char temp;
15     
16     /*
17     ** 将s_end指向最后一个字符,'\0'前面一个
18     */
19     while( *s_end++ != '\0' )
20         ;
21     s_end -= 2;
22     
23     /*
24     ** 交换字符
25     */
26     while( s_head < s_end )
27     {
28         temp = *s_head;
29         *s_head = *s_end;
30         *s_end = temp;
31         s_head ++;
32         s_end --;
33     }
34 }
35 
36 int 
37 main()
38 {
39     char str[] = "ABCDEFGH";
40     
41     reverse_string( str );
42     
43     puts( str );
44 }

 

posted on 2014-11-19 17:08  丝工木每  阅读(418)  评论(0编辑  收藏  举报

导航