forked from jaege/Cpp-Primer-5th-Exercises
-
Notifications
You must be signed in to change notification settings - Fork 0
/
9.44.cpp
31 lines (27 loc) · 902 Bytes
/
9.44.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <string>
#include <iostream>
void replaceStr(std::string &s,
const std::string &oldVal,
const std::string &newVal) {
// Use `<` operator, because it is possible that `pos` jumps over the end
for (std::string::size_type pos = 0; pos < s.size(); ) {
if (s.substr(pos, oldVal.size()) == oldVal) {
s.replace(pos, oldVal.size(), newVal);
pos += newVal.size();
} else
++pos;
}
}
int main() {
std::string s{"r u ok?\ngo thru\ntho tho altho\nthrough thruu"};
std::cout << "Old:\n" << s << std::endl;
replaceStr(s, "tho", "though");
std::cout << "\nNew:\n" << s << std::endl;
replaceStr(s, "thru", "through");
std::cout << "\nNew:\n" << s << std::endl;
replaceStr(s, "hl", "hello");
std::cout << "\nNew:\n" << s << std::endl;
replaceStr(s, "u", "you");
std::cout << "\nNew:\n" << s << std::endl;
return 0;
}