字符串翻转/反转(reverse a CStyle String)

问:Write code to reverse a C-Style String  (C-String means that “abcd” is  represented as fve characters, including the null character )

 

解:在不增加额外空间的条件下,使用两个指针:头指针和尾指针。

      头指针从字符串首部开始,不断递增;

      尾指针从字符串尾部(不是'\0')开始,不断递减;

      当头指针的地址小于尾指针的地址时,交换头、尾指针的内容。

 

码:

1  void reverse(char *str) {
2    char * end = str;
3    char tmp;
4    if (str) {
5      while (*end) {
6        ++end;
7      }
8      --end;
9      while (str < end) {
10        tmp = *str;
11        *str++ = *end;
12        *end-- = tmp;
13      }
14    }
15  }

原文地址:https://www.cnblogs.com/burellow/p/2348826.html