Strings: Length
Let's write a function which would return the number of characters in a string–in other words, the length of the string. As we just learned when we talked about iterating a string, to do that, we need to write a loop and iterate until we find the zero character at the end of the string, and count how many non-zero characters we saw.
Try it now:
#include <stdio.h>
int strlen(char *s) {
// TODO: your code here
}
int main() {
printf("Length of <%s> is %d\n", "123", strlen("123"));
printf("Length of <%s> is %d\n", "abcd efgh", strlen("abcd efgh"));
printf("Length of <%s> is %d\n", "", strlen(""));
printf("Length of <%s> is %d\n", "a", strlen("a"));
return 0;
}
Note that we haven't started reading strings from the input yet; we'll learn how to do it soon.
You could've implemented the loop in strlen as a for or while loop with a counter, something like
int length = 0;
int i;
for (i = 0; s[i]; ++i) {
++length;
}
or you could probably use a pointer instead of an index:
int length = 0;
for ( ; *s; ++s) {
++length;
}
It's not immediately obvious that you don't need a length variable if you don't change your parameter. Indeed: let s be your function parameter, then if you iterate using a different pointer:
char *p = s;
while (*p) {
++p;
}
or, same thing,
char *p;
for (p = s; *p; ++p) {
// do nothing inside for
}
then the final length of the string will be p - s: the difference between two pointers, so return p - s will be your answer. I suggest that you spend some time and try different approaches, and verify that they all work.
Now, the good news is that you don't need to reimplement the strlen function every time you need it. Actually, it's a standard function, and the first function from <string.h> we learn about. So, whenever you need to know the length of any string, you can just add one more #include:
#include <string.h>
and then use the standard strlen.
Note that the real strlen returns a value of a special type size_t; we'll talk about it later, it's basically an unsigned–that is, non-negative–integer. We haven't talked about the unsigned types yet.
More string functions will follow!