2. string length
The length of a string is the number of characters in it, not including the terminating zero byte.strlen( "hi") is 2 strlen( "") is 0It's easy to compute a string length. Given an array of characters s containing a string:
int len = 0; while( s[len] != '\0') ++len;If `len' is the length of a string s, then s[0]...s[len-1] are the characters in the string,
and s[len] is the terminating zero byte.
Putting the above into a function:
int strlen( char s[]) { int len = 0; while( s[len] != '\0') ++len; return len; }The standard C library definition of strlen is similar, but since the length of a string can not be negative, `size_t', the unsigned integral type returned by sizeof, is used instead of int.
Also, since strlen() does not modify the string contents, the string argument can be declared as an array of constant characters:
size_t strlen( const char s[])The `const' in the declaration tells the user that the function does not modify the string contents,
and it tells the compiler to generate an error message if the function definition attempts to modify the string contents.
Since C does not pass arrays to functions, only the array starting address, array arguments are usually declared using address (pointer) notation,
though it really makes no difference in writing the function:
size_t strlen(const char *s) { size_t len = 0; while( s[len] != '\0') ++len; return len; }