Last active
January 15, 2023 10:35
-
-
Save RichardB01/ba85a20b22efa138b4d58cdaa60e5b69 to your computer and use it in GitHub Desktop.
A function that replaces a character in a given string with another.
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 <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