
The string type comes with tools built in. You call them with a dot: s.size(), s.substr(...) and so on.
ON THIS PAGE
SHOW EXAMPLE IN
//THE EXAMPLE
main.cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "Ulaanbaatar";
cout << s.size() << endl; // 11
cout << s.substr(0, 5) << endl; // Ulaan
cout << s.find("baatar") << endl; // 5
string num = "42";
int n = stoi(num) + 1;
cout << n << endl; // 43
return 0;
}> what you see
11 Ulaan 5 43
//LINE BY LINE
Watch it run
s = Ulaanbaatar. Eleven characters, numbered 0 through 10.
The toolbox
| You write | What it does |
|---|---|
s.size() | урт / the length |
s.empty() | хоосон эсэх / is it empty? |
s[i] | i дугаарт тэмдэгт / the character at i |
s.substr(a, n) | хэсэг таслах / take a piece |
s.find(t) | t хаана байгаа / where t starts |
s + t | залгах / join them |
stoi(s) · to_string(n) | тоо ↔ мөр / number ↔ text |
Upper and lower case
toupper and tolower work on one character. Converting a whole string needs a loop.
#include <cctype>
string s = "hello";
for (int i = 0; i < s.size(); i++) {
s[i] = toupper(s[i]);
}
cout << s; // HELLO> what you see
HELLO
Comparing strings
You can compare a string directly with ==, < and >. The order used is dictionary order.
string a = "apple", b = "banana";
cout << (a == b) << endl; // 0 (худал)
cout << (a < b) << endl; // 1 (үнэн — a эхэлж ирнэ)> what you see
0 1
Case matters: "Apple" == "apple" is false.