forked from pezy/CppPrimer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathex9_44.cpp
34 lines (30 loc) · 784 Bytes
/
ex9_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
32
33
34
//
// ex9_44.cpp
// Exercise 9.44
//
// Created by pezy on 12/4/14.
// Copyright (c) 2014 pezy. All rights reserved.
//
// @Brief Rewrite the previous function using an index and replace.
// @See 9.43
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;
using std::prev;
void Replace(string& s, string const& oldVal, string const& newVal)
{
for (string::size_type i = 0; i != s.size(); ++i)
if (s.substr(i, oldVal.size()) == oldVal) {
s.replace(i, oldVal.size(), newVal);
i += newVal.size() - 1;
}
}
int main()
{
string str{"To drive straight thru is a foolish, tho courageous act."};
Replace(str, "tho", "though");
Replace(str, "thru", "through");
cout << str << endl;
}