Strings are sequences of zero or more characters. String literals are character strings surrounded by quotation marks. String literals can include any valid character, including white-space characters and character escape sequences. Once stored as a string literal, modification of the string leads to undefined results.
In the following example, ABC
is the string literal. It
is assigned to a character array where each character in the string
literal is stored as one array element. Storing a string literal in
a character array lets you modify the characters of the array.
char x[] = "ABC";
String literals are typically stored as arrays of type
char
(or wchar_t
) if prefaced with an
L
, and have static storage duration.
The following declaration declares a character array to hold the string "Hello!":
char s[] = "Hello!";
The character array s
is initialized with the
characters specified in the double quotation marks, and terminated
with a null character (\0
) . The null character marks
the end of each string, and is automatically concatenated to the end
of the string literal by the compiler. Adjacent string literals are
automatically concatenated (with a single null character added at
the end) to reduce the need for the line continuation character (the
backslash at the end of a line).
Following are some valid string literals:
"" /* Here's a string with only the null character */ "You can have many characters in a string." "\"You can mix characters and escape sequences.\"\n" "Long lines of text can be continued on the next line \ by using the backslash character at the end of a line." "Or, long lines of text can be continued by using " "ANSI's concatenation of adjacent string literals." "\'\n" /* Only escape sequences are in this string */
To determine the length of a given string literal (not including
the null character), use the strlen
function. See Chapter 9 for more information on other
library routines available for string manipulation.