Skip to content

Instantly share code, notes, and snippets.

@magemore
Last active February 2, 2016 21:24
Show Gist options
  • Save magemore/960109456030b2068f7a to your computer and use it in GitHub Desktop.
Save magemore/960109456030b2068f7a to your computer and use it in GitHub Desktop.
c++ php str_replace analog using std string
std::wstring str_replace(std::wstring search, std::wstring replace, std::wstring subject)
{
std::wstring result = subject;
if (subject.length() == 1) {
if (subject == search) return replace;
}
else if (subject.length() > 1) {
std::string::size_type start_pos = 0;
std::string::size_type search_length = search.length();
std::string::size_type replace_length = replace.length();
std::string::size_type found_pos = result.find(search, start_pos);
while (std::string::npos != found_pos) {
result = result.replace(found_pos, search_length, replace);
start_pos = found_pos + replace_length;
found_pos = result.find(search, start_pos);
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment