Monday, May 24, 2010

C program, use recursive method find string length?

why do I get the feeling that this sounds like a homework assignment? I am giving a very small code that demonstrates the principle. I absolutely will not recommend something like this for any form of deployment





#include %26lt;stdio.h%26gt;





int findlen(char * s) {


int len;


if (*s == '\0') {


return 0;


}


len = findlen(s+1);


return len+1;


}





int main() {


char str[25]="hello world test";


int len = findlen(str);


printf("length = %d\n", len);


}

C program, use recursive method find string length?
U will find the code here:


http://www.codeguru.com/forum/showthread...
Reply:Strings in c are represented as some series of ascii characters followed by the NULL ascii character (represented numerically as 0). So, to do it recursively, our else case increments some variable (the length of the string) while our base case checks to see if the current location in the string is 0 or not. If so, we are done.





//assume we have the value at pointer length is initialized to 0


char strlen (char* s, int* length) {


if (!*s) {


return;


}


else{


*length++;


strlen(s++,length);


}


}





It could be written more efficiently, but you get the idea.
Reply:See here, you may find the answer: http://www.codeproject.com


No comments:

Post a Comment