string c 2b 2b replace

Solutions on MaxInterview for string c 2b 2b replace by the best coders in the world

showing results for - "string c 2b 2b replace"
Isabella
04 Jul 2019
1#include <cassert>
2#include <cstddef>
3#include <iostream>
4#include <string>
5#include <string_view>
6 
7std::size_t replace_all(std::string& inout, std::string_view what, std::string_view with);
8std::size_t remove_all(std::string& inout, std::string_view what);
9void test_replace_remove_all();
10 
11int main()
12{
13    std::string str{"The quick brown fox jumps over the lazy dog."};
14 
15    str.replace(10, 5, "red"); // (5)
16 
17    str.replace(str.begin(), str.begin() + 3, 1, 'A'); // (6)
18 
19    std::cout << str << "\n\n";
20 
21    test_replace_remove_all();
22}
23 
24 
25std::size_t replace_all(std::string& inout, std::string_view what, std::string_view with)
26{
27    std::size_t count{};
28    for (std::string::size_type pos{};
29         inout.npos != (pos = inout.find(what.data(), pos, what.length()));
30         pos += with.length(), ++count) {
31        inout.replace(pos, what.length(), with.data(), with.length());
32    }
33    return count;
34}
35 
36std::size_t remove_all(std::string& inout, std::string_view what) {
37    return replace_all(inout, what, "");
38}
39 
40void test_replace_remove_all()
41{
42    std::string str2{"ftp: ftpftp: ftp:"};
43    std::cout << "#1 " << str2 << '\n';
44 
45    auto count = replace_all(str2, "ftp", "http");
46    assert(count == 4);
47    std::cout << "#2 " << str2 << '\n';
48 
49    count = replace_all(str2, "ftp", "http");
50    assert(count == 0);
51    std::cout << "#3 " << str2 << '\n';
52 
53    count = remove_all(str2, "http");
54    assert(count == 4);
55    std::cout << "#4 " << str2 << '\n';
56}
queries leading to this page
c 2b 2b replacestring c 2b 2b replace