8.4 String Functions
As indicated earlier, C includes a collection of functions in its standard library for working with strings. The functions are defined in the <string.h> module. We will explore some of these functions in this and the following sections.
The length of a string is indicated by the number of characters that it contains. This value can be computed using the strlen function.
|
The String Length Function
string.h
int strlen(char str[]);
The function takes a string as an argument and returns as an integer the number of characters that it contains.
|
Consider the following declarations
- char message[] = "Hello, World";
- int size;
then the function call
- size = strlen(message);
will return 12, the number of characters in the string "Hello, World". As indicated earlier the null character is not included in the size since it is not a character in the string. It is only used to indicate the end of the string.
The Suppose we want to print the string in reverse order, all on one line. This can not be done with the
|
Consider the following array declarations:
- char name[35] = "John Smith";
- char text[50] = "";
Indicate what is returned by each of the given function calls.
| Statement | Result | Explanation |
|---|---|---|
size = strlen(name); |
10 | name contains the string "John Smith" which contains 10 characters. |
size = strlen(text); |
0 | The string array contains the empty string, which contains no characters. |
Consider the following array declarations:
- char memo[35];
What is the result of executing the following statement?
- int len = strlen(memo);
The results are unpredictable since the memo character array was not initialized with a string.


