std::string
std::string
- dynamic array of
char
(almost like vector<char>
)
- concatenation with
+
or +=
- single character access with
[index]
- modifiable ("mutable") unlike in e.g., Python or Java
- deeply copyable, deeply comparable
#include <string>
std::string hw = "Hello";
std::string s = hw;
hw += " World!";
cout << hw << '\n';
cout << hw[4] << '\n';
cout << s << '\n';
char
= std::string
's Element Type
char
char
- one
char
can hold a single character
- smallest integer type (usually 1 byte)
char
literals must be enclosed in single quotes:
'a'
, 'b'
, 'c'
, …
char c1 = 'A';
char c2 = 65;
cout << c1 << '\n';
cout << c2 << '\n';
cout << (c1 == c2) << '\n';
std::string s = "xyz";
s[1] = c1;
cout << s << '\n';
s += c2;
cout << s << '\n';
Special Characters
backslash \
acts as escape character
\n |
new line |
"Line1\nLine1\nLine3" |
\t |
tab |
"Column1\tColumn1\tColumn3" |
\' |
single quote |
"he said \'quote\' to me" |
\" |
double quote |
"he said \"quote\" to me" |
\\ |
backslash itself |
"C:\\Users\\me\\hello.cpp" |
std::string
Manipulation
Manipulation
'a' |
char |
|
"C-string literal" |
char const[] |
|
"std string literal"s |
std::string |
C++14 |
"xyz"
is a "C-string"
auto a = "seven of";
auto b = a;
a += " nine";
auto c = "al" + "cove";
std::string s = a;
s += " nine";
"xyz"s
is a std::string
C++14
#include <string>
using namespace std::string_literals;
auto s1 = "seven of"s;
auto s2 = s1;
s1 += " nine";
cout << s1 << '\n';
cout << s2 << '\n';
auto s3 = "uni"s + "matrix"s;
cout << s3 << '\n';
String literals that are only separated by whitespace are joined:
"first" "second"
⇒
"first second"
std::string b = "This is one literal"
"split into several"
"source code lines!";
Raw String Literals
Advantage:
special characters can be used without escaping
R"(raw "C"-string c:\users\joe )" |
char const[]} |
C++11 |
R"(raw "std"-string c:\users\moe )"s |
std::string |
C++14 |
std::getline
getline
- read entire lines / chunks of text at once
- target string can be re-used (saving memory)
std::string s;
getline(std::cin, s);
getline(std::cin, s, '\t');
getline(std::cin, s, 'a');