1// string::substr
2#include <iostream>
3#include <string>
4
5int main ()
6{
7 std::string str="We think in generalities, but we live in details.";
8 // (quoting Alfred N. Whitehead)
9
10 std::string str2 = str.substr (3,5); // "think"
11
12 std::size_t pos = str.find("live"); // position of "live" in str
13
14 std::string str3 = str.substr (pos); // get from "live" to the end
15
16 std::cout << str2 << ' ' << str3 << '\n';
17
18 return 0;
19}
1#include <string>
2#include <iostream>
3
4int main()
5{
6 std::string a = "0123456789abcdefghij";
7
8 // count is npos, returns [pos, size())
9 std::string sub1 = a.substr(10);
10 std::cout << sub1 << '\n';
11
12 // both pos and pos+count are within bounds, returns [pos, pos+count)
13 std::string sub2 = a.substr(5, 3);
14 std::cout << sub2 << '\n';
15
16 // pos is within bounds, pos+count is not, returns [pos, size())
17 std::string sub4 = a.substr(a.size()-3, 50);
18 // this is effectively equivalent to
19 // std::string sub4 = a.substr(17, 3);
20 // since a.size() == 20, pos == a.size()-3 == 17, and a.size()-pos == 3
21
22 std::cout << sub4 << '\n';
23
24 try {
25 // pos is out of bounds, throws
26 std::string sub5 = a.substr(a.size()+3, 50);
27 std::cout << sub5 << '\n';
28 } catch(const std::out_of_range& e) {
29 std::cout << "pos exceeds string size\n";
30 }
31}