forked from pezy/CppPrimer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ex9_43.cpp
62 lines (58 loc) · 1.9 KB
/
ex9_43.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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
//
// ex9_43.cpp
// Exercise 9.43
//
// Created by pezy on 6/18/15.
// Updated by sanerror on 10/16/16.
// Copyright (c) 2014 pezy. All rights reserved.
//
// @Brief Write a function that takes three strings, s, oldVal, and newVal.
// Using iterators, and the insert and erase functions replace
// all instances of oldVal that appear in s by newVal.
// Test your function by using it to replace common abbreviations,
// such as "tho" by "though" and "thru" by "through".
#include <string>
using std::string;
#include <iostream>
void Replace(string& s, const string& oldVal, const string& newVal)
{
for (auto beg = s.begin(); std::distance(beg, s.end()) >=
std::distance(oldVal.begin(), oldVal.end());) {
if (string{beg, beg + oldVal.size()} == oldVal) {
beg = s.erase(beg, beg + oldVal.size());
beg = s.insert(beg, newVal.cbegin(), newVal.cend());
std::advance(beg, newVal.size());
}
else
++beg;
}
}
int main()
{
{
string str{"To drive straight thru is a foolish, tho courageous act."};
Replace(str, "thru", "through");
Replace(str, "tho", "though");
std::cout << str << std::endl;
}
{
string str{
"To drive straight thruthru is a foolish, thotho courageous act."};
Replace(str, "thru", "through");
Replace(str, "tho", "though");
std::cout << str << std::endl;
}
{
string str{"To drive straight thru is a foolish, tho courageous act."};
Replace(str, "thru", "thruthru");
Replace(str, "tho", "though");
std::cout << str << std::endl;
}
{
string str{"my world is a big world"};
Replace(str, "world",
"worldddddddddddddddddddddddddddddddddddddddddddddddd");
std::cout << str << std::endl;
}
return 0;
}