A String is a String
In
Part 8-1
we defined a string as
-
A string may be an empty string.
-
A string may be a character followed by a string.
Using that definition of a string we may define the length
of a string as:
-
The length of the empty string is 0.
-
The length of a non-empty string is 1 plus the length
of the string which follows the first character.
From this definition of the length, we may develop a
recursive function to compute the length:
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 it 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 hand if the character we're pointing to is not 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 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.