# C++ Notes: C-Strings

## Strings

There are two ways to represent character strings in C++.

1. Arrays of characters, terminated by a "zero" value, are commonly used. These are referred to as "c-strings" to distinguish them from the `string` type that was introduced in the C++ Standard Template Library.
2. The `string` class is a relatively late addition to C++ that represents strings as objects. This class is generally easier to use than c-strings, but you usually can not avoid some use of c-strings.

## Characters

Individual characters (type `char`) are stored in single bytes. A character literal is surrounded by single quotes (eg, 'a', ')', ...). Double quotes are used to represent a c-string literal. Eg, "a" is a c-string consisting of one character followed by a zero. Some characters need to be preceded by a special escape character (the backslash), because they have some meaning to the compiler. For example, '\'' is a single quote, '\\' is a single backslash, '\n' is the newline character, and there are others.

## Arrays of Characters terminated with "zero"

C-strings are stored as characters in an array. Following the characters there is a character with code zero. You can write this as either 0 or '\0'. The name for this ASCII character is NUL, but that should not be confused with the special pointer value NULL (which should not be used for this purpose).

## Quoted Strings

A double-quoted string of characters is a common way to write an array of characters. The string `"Hello"` represents and array of six (not 5) characters. The last character is the terminating zero code. Example,

    char greeting[] = "Hello";

is the same as

    char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

## Using a quoted string as an array

A quoted string really represents an array, so it can even be subscripted. For example,

    for (int i=0; i<5; i++) {
        cout << "Hello"[i];
    }

## Include files

If you are using the c-string and character functions, you must have

    #include <cstring>
    #include <cctype>
| or for old compilers |
    #include <string.h>
    #include <ctype.h>