Skip to content

Instantly share code, notes, and snippets.

@RichardB01
Last active January 15, 2023 10:35
Show Gist options
  • Save RichardB01/ba85a20b22efa138b4d58cdaa60e5b69 to your computer and use it in GitHub Desktop.
Save RichardB01/ba85a20b22efa138b4d58cdaa60e5b69 to your computer and use it in GitHub Desktop.
A function that replaces a character in a given string with another.
#include <string>
using namespace std;
/**
* Replaces every occurance of repchar with newchar in the str
* and returns a copied value.
* @param[in] str The string who's characters are being replaced.
* @param[in] repchar The character to replace.
* @param[in] newchar The character to replace with.
* @param[out] The copied string with replaced characters.
*/
string replacechar(string str, char repchar, char newchar) {
string replacedstr;
/**
* Copy the characters one by one into the new string
* but if the character being copyed needs to be replaced
* then insert the replaced character instead.
*/
for (uint32_t charindex = 0u; charindex < str.length(); charindex++) {
char currchar;
currchar = str.at(charindex);
if (currchar == repchar) {
replacedstr.push_back(newchar);
} else {
replacedstr.push_back(currchar);
}
}
return replacedstr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment