反转字符串

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

SOLUTION


 

The only "gotcha" is to try to do it in place, and to be careful for the null character.

 1 #include <stdio.h>
 2 void reverse(char *str){
 3     char *end = str;
 4     char tmp;
 5     if(str) {
 6         while(*end){
 7             ++end;
 8         }
 9         --end;
10         while(str < end) {
11             tmp = *str;
12             *str++ = *end;
13             *end-- = tmp;
14         }
15     }
16 }
17 
18 int main() {
19     char s[] = "abcdef";//不要写成char *s = "abcdef";因为s指向字符串常量,不能改变字符串常量的值
20     printf("%s\n",s);
21     reverse(s);
22     printf("%s\n",s);
23     return 0;
24 }

 

posted on 2013-02-26 22:09  yxconankid  阅读(128)  评论(0)    收藏  举报