字符串逆序打印
版本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\n",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\n",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 == '\0') { return; } reverse(p+1); strncat(g_buf,p,1); } int main() { char buf[] = "abcd"; memset(g_buf,0,sizeof(g_buf)); reverse(buf); printf("g_buf = %s\n",g_buf); return 0; }
版本4
使用栈将字符串存到传入的局部变量中
/*** str_reverse.c ***/ #include<stdio.h> #include<string.h> char g_buf[256]; void reverse(char *p) { if(NULL == p) { return ; } if(*p == '\0') { return; } reverse(p+1); strncat(g_buf,p,1); } int main() { char buf[] = "abcd"; memset(g_buf,0,sizeof(g_buf)); reverse(buf); printf("g_buf = %s\n",g_buf); return 0; }