Write a function reverse_string (char * string)
Implementation: To reverse-arrange the characters in the argument string.
Requirement: You cannot use the string manipulation function in the C function library.
Non-recursive implementation
void reverse (char *str) {char *left = Str;char *right = str + strlen (str)-1;while (left < right) {char tmp = *left;*lef t = *right;*right = tmp;left++;right--;}}
2. Recursive implementations
#include <stdio.h> #include <stdlib.h> #include <string.h>int main () {char* reverse_string (char * String,int len); int I,len=0;char arr[]= "ABCD"; Len=strlen (arr), Char Ret[len];char *p=arr;for (i=0;i<len;i++) ret[i]=* (reverse_string (P,len));p rintf ("%s\n", ret ); System ("pause"); return 0;} char* reverse_string (char * string,int len) {int static J=0;char s[len]= "0"; if (*string== ') ' Return s;else{s[len-j]=* String;j++;reverse_string (string++);}}
Recursive optimization:
int length (char *str) {int count = 0;while (*str) {count++;str++;} return count;} void reverse (char *str) {int len = length (str); if (len== 0) {return;} Else{char tmp = *STR;*STR = * (str + len-1); * (str + len-1) = ' + '; reverse (1+STR); * (str + len-1) = tmp;}} int main () {char arr[] = "Bit-tech"; reverse (arr);p rintf ("%s\n", arr); System ("pause"); return 0;}
The recursive call graph is as follows 650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M02/7D/C7/wKioL1bv5XeRSOXgAABROF8tc38779.png "title= "Untitled. png" Width= "height=" 472 "border=" 0 "hspace=" 0 "vspace=" 0 "style=" width:1000px;height:472px; "alt=" Wkiol1bv5xersoxgaabrof8tc38779.png "/>
This article is from the "sunshine225" blog, make sure to keep this source http://10707460.blog.51cto.com/10697460/1753594
Recursively implement string rollover