std::string#include <string> is a container that holds text. It grows and shrinks as needed and frees its memory automatically. The characters are stored contiguously on the heap, though most implementations keep short strings inside the object itself to avoid an allocation. It is available from the string header:
#include <string>
std::string#include <string> s = "hello";Strings can be concatenated with + and +=:
std::string#include <string> a = "hello";
std::string#include <string> b = a + " world";
b += "!";
std::cout#include <iostream> << b << "\n"; // hello world!size() returns the number of characters and empty() checks whether the string has no characters:
std::string#include <string> s = "hello";
s.size(); // 5
s.empty(); // falseCharacters are accessed with [], or at() which throws std::out_of_range#include <stdexcept> when the index is out of range:
std::string#include <string> s = "hello";
s[0]; // 'h'
s.at(0); // 'h'
s.at(10); // Throws std::out_of_range#include <stdexcept>.
s[0] = 'j'; // s is now "jello".Strings compare by content with the usual operators:
std::string#include <string> a = "apple";
std::string#include <string> b = "banana";
a == b; // false
a < b; // true, lexicographical.Common operations include finding and extracting substrings:
std::string#include <string> s = "hello world";
s.find("world"); // 6
s.find("xyz"); // std::string#include <string>::npos
s.substr(0, 5); // "hello"c_str() returns the contents as a null-terminated C-string, for passing to functions that expect a const char*:
std::string#include <string> s = "hello";
std::printf("%s\n", s.c_str());Note
Prefer std::string#include <string> over C-style char arrays. A C-string is a raw array with a null terminator and no size, so concatenation, comparison and resizing all need manual function calls and are easy to get wrong.
Numbers can be converted to and from strings:
std::string#include <string> s = std::to_string#include <string>(42); // "42"
int n = std::stoi#include <string>("123"); // 123
double d = std::stod#include <string>("3.14"); // 3.14std::stoi#include <string> and std::stod#include <string> throw an exception if the string does not start with a number:
std::stoi#include <string>("abc"); // Throws std::invalid_argument#include <stdexcept>.
std::stoi#include <string>("12ab"); // 12, trailing characters are ignored.
Dan