Created
December 4, 2018 03:47
-
-
Save GenesisFR/cceaf433d5b42dcdddecdddee0657292 to your computer and use it in GitHub Desktop.
C++ function to replace all occurrences of a substring in a string
This file contains 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
using namespace std; | |
string replaceAll(string str, const string &from, const string &to) | |
{ | |
size_t start_pos = 0; | |
while ((start_pos = str.find(from, start_pos)) != string::npos) | |
{ | |
str.replace(start_pos, from.length(), to); | |
start_pos += to.length(); // Handles case where 'to' is a substring of 'from' | |
} | |
return str; | |
} | |
int main() | |
{ | |
string errString = "This docment uses 3 other docments to docment the docmentation"; | |
string correctString = replaceAll(errString, "docment", "document"); | |
return 0; | |
} |
In native C++, it seems to only replace one occurrence of a substring and you have to give it the offsets: https://cplusplus.com/reference/string/string/replace/
In C++/CLI, like the example you've shown above, it replaces all occurrences of the substring: https://learn.microsoft.com/en-us/dotnet/api/system.string.replace
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yes, I do. Does C++ not natively perform a Replace All when calling
mystring->Replace("'", "")
? I'm asking because my company is using a function that replaces the first quote, but I'm not sure it replaces all quotes.Here's the code that troubles me: