Skip to content

Instantly share code, notes, and snippets.

@mdukat
Last active September 13, 2023 20:03
Show Gist options
  • Save mdukat/1abbc7010dde0649a9ae615d3428131b to your computer and use it in GitHub Desktop.
Save mdukat/1abbc7010dde0649a9ae615d3428131b to your computer and use it in GitHub Desktop.
Python-like string replace method for C++
#include <iostream>
#include <string>
int preplace(std::string& input, const std::string& a, const std::string& b){
size_t index;
int n = 0;
while((index = input.find(a,0)) != std::string::npos){
input.replace(index, a.size(), b);
n++;
}
return n;
}
int main() {
std::string myString = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?";
std::cout << myString << std::endl;
preplace(myString, "wood", "rock");
std::cout << myString << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment