Sams Teach Yourself C in 21 Days

(singke) #1
string—the number of characters it contains. This length is obtained with the library
functionstrlen(). Its prototype, in string.h, is
size_t strlen(char *str);
You might be puzzling over the size_treturn type. This type is defined in string.h as
unsigned, so the function strlen()returns an unsigned integer. The size_ttype is used
with many of the string functions. Just remember that it means unsigned.
The argument passed to strlenis a pointer to the string whose length you want to know.
The function strlen()returns the number of characters between strand the next null
character, not counting the null character. Listing 17.1 demonstrates strlen().

LISTING17.1 strlen.c. Using the strlen()function to determine the length of a string
1: /* Using the strlen() function. */
2:
3: #include <stdio.h>
4: #include <string.h>
5:
6: int main( void )
7: {
8: size_t length;
9: char buf[80];
10:
11: while (1)
12: {
13: puts(“\nEnter a line of text, a blank line to exit.”);
14: gets(buf);
15:
16: length = strlen(buf);
17:
18: if (length != 0)
19: printf(“\nThat line is %u characters long.”, length);
20: else
21: break;
22: }
23: return 0;
24: }

Enter a line of text, a blank line to exit.
Just do it!
That line is 11 characters long.
Enter a line of text, a blank line to exit.

482 Day 17

INPUT/
OUTPUT

28 448201x-CH17 8/13/02 11:13 AM Page 482

Free download pdf