forked from Mooophy/Cpp-Primer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathex9_44.cpp
35 lines (31 loc) · 781 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
35
//
// ex9_44.cpp
// Exercise 9.44
//
// Created by XDXX on 4/17/15.
// Copyright (c) 2015 XDXX. 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;
void func(string &s, string const& oldVal, string const& newVal)
{
for (size_t pos = 0; pos <= s.size() - oldVal.size();) {
if (s[pos] == oldVal[0] && s.substr(pos, oldVal.size()) == oldVal) {
s.replace(pos, oldVal.size(), newVal);
pos += newVal.size();
}
else
++pos;
}
}
int main()
{
string str{"To drive straight thru is a foolish, tho courageous act."};
func(str, "tho", "though");
func(str, "thru", "through");
cout << str << endl;
return 0;
}