Chapter 3
Strings, Vectors and Arrays
2 minute read
Library string type
Initialization
string s1; // default initialization; s1 is empty string
string s2 = s1; // s2 is a copy of s1
string s3 = "hiya"; // s3 is a copy of the string literal
string s4(3, 'o'); // s4 is ooo
string s5 = "hiya"; // copy initialization
string s6("hiya"); // direct initialization
string s7(4, 'o'); // direct initialization
string s8 = string(4, 'o'); // copy initialization using temporary object
Operations on strings
Operations can be defined by names (memeber functions) and operators symbols (+, «, », +=).
| Expression | Description |
|---|---|
os << s | Writes s onto output stream os. Returns os. |
is >> s | Reads whitespace-separated string from is into s. Returns is. |
getline(is, s) | Reads a line of input from is into s. Returns is. |
s.empty() | Returns true if s is empty; otherwise returns false. |
s.size() | Returns the number of characters in s. |
s[n] | Returns a reference to the char at position n in s; positions start at 0. |
s1 + s2 | Returns a string that is the concatenation of s1 and s2. |
s1 = s2 | Replaces characters in s1 with a copy of s2. |
s1 == s2 | The strings s1 and s2 are equal if they contain the same characters. Equality is case-sensitive. |
s1 != s2 | Inequality check; case-sensitive. |
<, <=, >, >= | Comparisons are case-sensitive and use dictionary ordering. |