Skip to content

Instantly share code, notes, and snippets.

@GenesisFR
Created December 4, 2018 03:47
Show Gist options
  • Save GenesisFR/cceaf433d5b42dcdddecdddee0657292 to your computer and use it in GitHub Desktop.
Save GenesisFR/cceaf433d5b42dcdddecdddee0657292 to your computer and use it in GitHub Desktop.
C++ function to replace all occurrences of a substring in a string
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;
}
@WiktoRPetR
Copy link

Hello
Tell me, if I need to change all substrings of type "cos" to a substring of the "sin" type in several files, when downloading from the network. The file name is not known. We use C ++. How to do it?

@GenesisFR
Copy link
Author

If you have a comment regarding the function above, post here, otherwise you can ask on StackOverflow.

@nickpreston24
Copy link

nickpreston24 commented Dec 16, 2022

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:

String^ BaseForm::SafeString(Object^ strVal)
{
	String^ strRetVal = strVal->ToString();
	if (strVal != nullptr)
	{
		strRetVal = strRetVal->Replace("'", "''");
		strRetVal = strRetVal->TrimEnd();
	}
	return strRetVal;
}

@GenesisFR
Copy link
Author

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