首页 > 代码库 > 小试牛刀之反转字符串

小试牛刀之反转字符串

最近玩儿python玩上瘾了,突然想念c语言,所以,休闲下:
解法一:如果没有对申请外部空间有所限制,那就先试试这个喽:

1 void invert_str1(char *old_str, char *new_str)2 {3     int i = strlen(old_str)-1;4     int j = 0;5     if (old_str == NULL) printf("error!"), exit(1);6     bzero(new_str, sizeof(new_str));7     for ( ; new_str[j] = old_str[i]; i--, j++) ;8 }

 解法二:哪有解法一那样的好事,一般都会有申请空间的限制的;

 1 void invert_str2(char *str) 2 { 3     int i, j; 4     if (str == NULL) printf("error!"), exit(1); 5     for (i = 0, j = strlen(str)-1; i < j; i++, j--) { 6         str[j] = str[i] ^ str[j]; 7         str[i] = str[i] ^ str[j]; 8         str[j] = str[i] ^ str[j]; 9         }10 }

 解法三:可是毕竟玩儿的是c语言嘛,还是耍一耍指针比较爽:

 1 void invert_str3(char *str)     2 { 3     char *p = str; 4     char *q = str + strlen(str) - 1; 5     if (str == NULL) printf("error!"), exit(1); 6     while (p < q) { 7         *q = *p ^ *q; 8         *p = *p ^ *q; 9         *q = *p ^ *q;10         p++, q--;11         }12 }    

解法四:玩着玩着忽然想起来,交换两个变量还可以这么写的:

 1 void invert_str4(char *str)     2 { 3     char *p = str; 4     char *q = str + strlen(str) - 1; 5     if (str == NULL) printf("error!"), exit(1); 6     while (p < q) { 7         *p = *p + *q; 8         *q = *p - *q; 9         *p = *p - *q;10         p++, q--;11         }12 }    

解法五:还有啥可玩儿的吗?哦,对了,别忘了递归啊,再来个递归爽一爽:

 1 void invert_str5(char *str, int len) 2 { 3     if (len <= 1); 4     else { 5         *str = *str ^ *(str+len-1); 6         *(str+len-1) = *str ^ *(str+len-1); 7         *str = *str ^ *(str+len-1); 8         invert_str5(str+1, len-2); 9         }10 }

总结:关键词 额外空间申请、指针、对换效率、递归;