A string is a sequence of characters
A string is a sequence of characters stored in order. Characters include letters, digits, spaces, and punctuation marks. Programs use strings to store and work with text, such as a name, a sentence, or a file path.
In C++ source code, a string is written inside double quotes. The literal "Hello" has five visible characters: H, e, l, l, and o. C++ also stores a hidden null character after them, as the next section shows.
A simple example with std::string
#include <iostream>
#include <string>
int main() {
std::string greeting = "Hello";
std::cout << greeting << '\n'; // Hello
std::cout << greeting.size() << '\n'; // 5
}
std::string comes from the <string> header. It is a class that keeps track of its own length. The size() member function returns the number of characters, which is 5 here.
The same text as a C-style string
A C-style string is an array of char. The array must end with a null character, written '\0', which marks where the text stops.
#include <cstring>
#include <iostream>
int main() {
char greeting[] = "Hello";
std::cout << greeting << '\n'; // Hello
std::cout << sizeof(greeting) << '\n'; // 6
std::cout << std::strlen(greeting) << '\n'; // 5
}
The array holds six bytes: five letters and the null character. sizeof reports the total size of the array, including the null character. std::strlen counts the characters before the null, so it returns 5.
So the two examples report different numbers for the same word. The std::string size is 5, and the array size is 6, because the array stores the null character.
Single characters and strings
Single quotes make a single character, and double quotes make a string. 'H' is one char. "H" is a string with one visible character and the hidden null character after it.
Why strings matter for joining text
Once you have strings, you can combine them. C++ offers several ways to do that. For the ways to join text, see how to concatenate strings in c.
Other things to do with strings
std::string has member functions such as size(), empty(), and substr(). For a list of the others, see c string methods. To visit each character in order, see how to iterate through a string in c.