-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathch2_ex2.cpp
More file actions
42 lines (34 loc) · 1.1 KB
/
ch2_ex2.cpp
File metadata and controls
42 lines (34 loc) · 1.1 KB
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
import <iostream>;
import <format>;
import <string>;
import <compare>;
import <string_view>;
using namespace std;
// The parameters are const references to avoid unnecessary copying.
string replace_all_needle(string_view haystack, string_view needle, string_view replacement)
{
// Make a copy of the haystack.
string result{ haystack };
auto position{ result.find(needle) };
while (position != string::npos) {
result.replace(position, needle.length(), replacement);
position = result.find(needle);
}
return result;
}
int main() {
string strSource;
cout << "Type a source string:" << endl;
getline(cin, strSource);
string strFind;
cout << "Type a string to find:" << endl;
getline(cin, strFind);
string strReplace;
cout << "Type a string to replace:" << endl;
getline(cin, strReplace);
string result{ replace_all_needle(strSource, strFind, strReplace) };
cout << "Source:" << strSource << endl;
cout << "Find:" << strFind << endl;
cout << "Replace:" << strReplace << endl;
cout << "Result:" << result << endl;
}