forked from Mooophy/Cpp-Primer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathex9_43_2.cpp
43 lines (38 loc) · 1.5 KB
/
ex9_43_2.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
//
// ex9_43_2.cpp
// Exercise 9.43
//
// Created by pezy on 4/17/2015.
// Copyright (c) 2015 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”.
// @notice This program could compiled with GCC well.But it doesn't use some c++11
// features.There is another version(ex9_43_1.cpp) of this exercise which
// using c++11 features.
#include <iterator>
#include <iostream>
#include <string>
#include <cstddef>
using std::cout; using std::endl; using std::string;
void func(string &s, string const& oldVal, string const& newVal)
{
for (auto iter = s.begin(); std::distance(iter, s.end()) >= static_cast<ptrdiff_t>(oldVal.size()); )
if (*iter == oldVal[0] && string(iter, std::next(iter, oldVal.size())) == oldVal) {
iter = s.erase(iter, std::next(iter, oldVal.size()));
size_t pos = std::distance(s.begin(), iter) + newVal.size();
s.insert(iter, newVal.begin(), newVal.end());
iter = std::next(s.begin(), pos);
} else ++iter;
}
int main()
{
string s{ "To drive straight thru is a foolish, tho courageous act." };
func(s, "tho", "though");
func(s, "thru", "through");
cout << s << endl;
return 0;
}