Strings are objects that represent sequences of characters. The standard string
class provides a simple, safe and versatile alternative to using explicit arrays of char
s when dealing with text and other sequences of characters. The C++ string
class is part of the std
namespace and was standardized in 1998.
// 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
// Constructing from a buffer of characters
std::string s1("Hello World");
std::string s2(s1, 5); // Copy first 5 characters of s1 into s2
// 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
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.
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, in all cases it has undefined behavior if index > size()
, but when index == size()
:
CharT()
(the null character) is returned.CharT()
(the null character) is returned.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
.