Answers for "c++ replace"

C++
4

c++ replace character in string

#include <algorithm>
#include <string>

void some_func() {
  std::string s = "example string";
  std::replace( s.begin(), s.end(), 'x', 'y'); // replace all 'x' to 'y'
}
Posted by: Guest on December-09-2020
1

C++ std::string find and replace

#include <string>
#include <regex>

using std::string;

string do_replace( string const & in, string const & from, string const & to )
{
  return std::regex_replace( in, std::regex(from), to );
}

string test = "Remove all spaces";
std::cout << do_replace(test, " ", "") << std::endl;
Posted by: Guest on July-04-2021
0

string c++ replace

#include <cassert>
#include <cstddef>
#include <iostream>
#include <string>
#include <string_view>
 
std::size_t replace_all(std::string& inout, std::string_view what, std::string_view with);
std::size_t remove_all(std::string& inout, std::string_view what);
void test_replace_remove_all();
 
int main()
{
    std::string str{"The quick brown fox jumps over the lazy dog."};
 
    str.replace(10, 5, "red"); // (5)
 
    str.replace(str.begin(), str.begin() + 3, 1, 'A'); // (6)
 
    std::cout << str << "\n\n";
 
    test_replace_remove_all();
}
 
 
std::size_t replace_all(std::string& inout, std::string_view what, std::string_view with)
{
    std::size_t count{};
    for (std::string::size_type pos{};
         inout.npos != (pos = inout.find(what.data(), pos, what.length()));
         pos += with.length(), ++count) {
        inout.replace(pos, what.length(), with.data(), with.length());
    }
    return count;
}
 
std::size_t remove_all(std::string& inout, std::string_view what) {
    return replace_all(inout, what, "");
}
 
void test_replace_remove_all()
{
    std::string str2{"ftp: ftpftp: ftp:"};
    std::cout << "#1 " << str2 << '\n';
 
    auto count = replace_all(str2, "ftp", "http");
    assert(count == 4);
    std::cout << "#2 " << str2 << '\n';
 
    count = replace_all(str2, "ftp", "http");
    assert(count == 0);
    std::cout << "#3 " << str2 << '\n';
 
    count = remove_all(str2, "http");
    assert(count == 4);
    std::cout << "#4 " << str2 << '\n';
}
Posted by: Guest on August-18-2021
0

c++ replace

#include <string>

str1.replace(pos,len,str2);
Posted by: Guest on October-05-2021

Code answers related to "c++ replace"

Browse Popular Code Answers by Language