std::string
suggest changeIntroduction
Strings are objects that represent sequences of characters. The standard string class provides a simple, safe and versatile alternative to using explicit arrays of chars when dealing with text and other sequences of characters. The C++ string class is part of the std namespace and was standardized in 1998.
Syntax
- // Empty string declaration
std::string s;
- // Constructing from const char* (c-string)
std::string s("Hello");
std::string s = "Hello";
- // Constructing using copy constructor
std::string s1("Hello");
std::string s2(s1);
- // Constructing from substring
std::string s1("Hello");
std::string s2(s1, 0, 4); // Copy 4 characters from position 0 of s1 into s2
- // Substring from a position through the end
std::string s1("Hello World");
std::string s2(s1, 5); // Copy from position 5 through the end (" World")
- // Construct using fill constructor (char only)
std::string s(5, 'a'); // s contains aaaaa
- // Construct using range constructor and iterator
std::string s1("Hello World");
std::string s2(s1.begin(), s1.begin()+5); // Copy first 5 characters of s1 into s2
Remarks
Before using std::string, you should include the header string, as it includes functions/operators/overloads that other headers (for example iostream) do not include.
Using const char* constructor with a nullptr leads to undefined behavior. Since C++23, constructing from the nullptr literal is a compile error (the nullptr_t constructor is deleted).
std::string oops(nullptr);
std::cout << oops << "\n";
The method at throws an std::out_of_range exception if index >= size().
The behavior of operator[] is a bit more complicated. It has undefined behavior if index > size(). If index == size():
- Through C++03, the const overload returns
CharT()and the non-const overload has undefined behavior. - Since C++11, both overloads return a reference to a character with value
CharT()(the null character). Modifying that character is undefined behavior.
Since C++14, instead of using "foo", it is recommended to use "foo"s, as s is a user-defined literal suffix, which converts the const char* "foo" to std::string "foo".
Note: you have to use the namespace std::string_literals or std::literals to get the literal s.