A string is a sequence of characters
A string is text stored in a program: a sequence of characters, such as Hello or Hello, world!. Strings show up in most programs, for names, messages, file paths and user input.
Each character in a string is one unit of text, such as a letter, a digit, a space or a punctuation mark.
Strings are written in double quotes
In C++, a string literal is written inside double quotes. A single character uses single quotes. The two are different kinds of values, and mixing them up is a common beginner error:
char letter = 'H'; // one character
std::string word = "Hello"; // a string of five characters
Even a string with one letter, such as "H", is a string and not a char.
A first example in C++
The standard library type for strings is std::string, which is declared in the <string> header. This short program creates a string, prints it, and shows its length:
#include <iostream>
#include <string>
int main() {
std::string greeting = "Hello, world!";
std::cout << greeting << '\n';
std::cout << "Length: " << greeting.size() << '\n';
return 0;
}
The output is:
Hello, world!
Length: 13
The size() function returns the number of characters. The comma, the space and the exclamation mark all count as characters, so the length is 13.
Characters have positions
Each character in a string has a position, called an index. Indexes start at 0, not 1. For the string Hello, the positions look like this:
| Index | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| Character | H | e | l | l | o |
For a string stored in word, word[1] gives e. This is why loops over a string usually count from 0 up to, but not including, size().
C-style strings
C has no string type of its own. Instead, a C-style string is an array of char that ends with a null character, written '\0'. You will still see this form in older code and in many C libraries. For example, char name[] = "Ada"; holds four values: A, d, a and the null terminator.
If arrays are new to you, see what is an array in c with an example. C++ also gives you std::string, which handles the length and the terminator for you, so most new C++ code uses it instead.
Where to go next
Once you know what a string is, the next question is usually how to look at each character. Can I iterate over a string? Yes, and the article on how to iterate through a string in c shows the loops that do it.