int strlen( char *s ) { if( *s == '\0' ) return( 0 ) ; else return( 1 + strlen( s + 1 )) ; }Here we represent the string as we did before, as a pointer to the first character. (You may not recognize this as how we've represented it before. Earlier we talked about a string being an array of characters and somewhere is must be. But also remember that any time we "pass" an array to a function, we are really passing a pointer to the beginning of the array.) So if the character we're pointing to is the null byte, then we have the empty string and we return 0 according to part 1 of the recursive definition of length. On the other had if the character we're pointing to is no the null byte then we must have a character followed by a string according to part 2 of the definition of a string. In that case, part 2 of the length definition says that we must return 1 plus the length of the string following that character. We'll we have the function
strlen()
to find the length of a string.
The only question is how do we refer to the string that follows
this character.
Since we're representing the string by a pointer to its first
character, we need to determine the place where the first
character of the remaining string is located.
If s
is the address of the whole
string, then s+1
must be the
address of the character that follows the first one and that
is, therefore, the first character of the remaining string.
Using a recursive declaration of a string, we may devise a recursive
algorithm for copying a string:
void strcpy( char *dest, char *src ) { if( *src == '\0' ) *dest = '\0' ; else { *dest = *src ; ... } }(Note that the
strcpy()
studied earlier doesn't have a void return
type; it actually returns the first argument.)
The ... represents a recursive call.
What should that line be?