版本1 两个指针从头到尾和从尾到头交换内容逆序
/*** str_reverse.c ***/ #include<stdio.h> #include<string.h> int main() { char buf[] = "abcdrfg"; int len = strlen(buf); char *p1 = buf; char *p2 = buf + len - 1; while(p1 < p2) { char c = *p1; *p1 = *p2; *p2 = c; ++p1; --p2; } printf("buf = %s ",buf); return 0; }
版本2
使用函数接口封装
/*** str_reverse.c ***/ #include<stdio.h> #include<string.h> int my_reverse(char *str) { int iRet = -1; if(NULL == str) { return iRet; } char *buf = str; int len = strlen(buf); char *p1 = buf; char *p2 = buf + len - 1; while(p1 < p2) { char c = *p1; *p1 = *p2; *p2 = c; ++p1; --p2; } } int main() { char buf[] = "abcdrfg"; my_reverse(buf); printf("buf = %s ",buf); return 0; }
版本三
使用栈特性将字符串存储到全局变量中
/*** str_reverse.c ***/ #include<stdio.h> #include<string.h> char g_buf[256]; void reverse(char *p) { if(NULL == p) { return ; } if(*p == '