In the last chapter you were introduced to arrays and you saw how using arrays of numerical values could make many programming tasks much easier. In this chapter you'll extend your knowledge of arrays by exploring how you can use arrays of characters. You'll frequently have a need to work with a text string as a single entity. As you'll see, C doesn't provide you with a string data type as some other languages do. Instead, C uses an array of elements of type char
to store a string.
In this chapter I'll show you how you can create and work with variables that store strings, and how the standard library functions can greatly simplify the processing of strings.
You'll learn the following:
You've already seen examples of string constants—quite frequently in fact. A string constant is a sequence of characters or symbols between a pair of double-quote characters. Anything between a pair of double quotes is interpreted by the compiler as a string, including any special characters and embedded spaces. Every time you've displayed a message using printf()
, you've defined the message as a string constant. Examples of strings used in this way appear in the following statements:
printf("This is a string.");
printf("This is on
two lines!");
printf("For " you write \".");
These three example strings are shown in Figure 6-1. The decimal value of the character codes that will be stored in memory are shown below the characters.
Figure 6-1. Examples of strings in memory
The first string is a straightforward sequence of letters followed by a period. The printf()
function will output this string as the following:
This is a string.
The second string has a newline character,
, embedded in it so the string will be displayed over two lines:
This is on
two lines!
The third string may seem a little confusing but the output from printf()
should make is clearer:
For " you write ".
You must write a double quote within a string as the escape sequence "
because the compiler will interpret an explicit "
as the end of the string. You must also use the escape sequence \
when you want to include a backslash in a string because a backslash in a string always signals to the compiler the start of an escape sequence.
As Figure 6-1 shows, a special character with the code value 0 is added to the end of each string to mark where it ends. This character is known as the null character (not to be confused with NULL
, which you'll see later), and you write it as