English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

4 answers

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

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);
}

2006-07-03 19:03:29 · answer #1 · answered by Neil 5 · 0 0

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.

2006-07-03 19:07:01 · answer #2 · answered by Steve T 3 · 0 0

U will find the code here:
http://www.codeguru.com/forum/showthread.php?t=303185

2006-07-03 19:06:23 · answer #3 · answered by Friend 2 · 0 0

See here, you may find the answer: http://www.codeproject.com

2006-07-03 19:07:58 · answer #4 · answered by Anonymous · 0 0

fedest.com, questions and answers