Last active
October 30, 2025 22:50
-
-
Save mdukat/1abbc7010dde0649a9ae615d3428131b to your computer and use it in GitHub Desktop.
Python-like string replace method for C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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