The replace function allow to change a character from a string, with another. using: replace(s.begin(), s.end(), 'X', 'Y'); But it is possible to change 2 or more different characters with one? for example: In string "Tell us more about your question", I want to change all "o, i, u" with "x". So at output it will be: Tell xs abxxt yxxr qxuestixn
-
Not a dublicate, this is another question with another sense, before asking it, I spend lot of time to search on stackoverflow my answerlidya_q– lidya_q2019-10-02 05:11:58 +00:00Commented Oct 2, 2019 at 5:11
-
Dear lidya I think your question is the same as stackoverflow.com/questions/37952240/…Nastaran Hakimi– Nastaran Hakimi2019-10-02 05:23:43 +00:00Commented Oct 2, 2019 at 5:23
-
@NastaranHakimi I will try to use your answer. thxlidya_q– lidya_q2019-10-02 14:19:46 +00:00Commented Oct 2, 2019 at 14:19
Add a comment
|
1 Answer
From another answer this should work:
void replaceAll(std::string& str, const std::string& from, const std::string& to) {
if(from.empty())
return;
size_t start_pos = 0;
while((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
}
}
Credit: Michael Mrozek on SO
2 Comments
lidya_q
I know that answer, and I don't like it, that's why I'm asking, I don't need to replace a particular range. for example there is an answer, to change "bc" with "!!", my question is, if there it's another function like replace, to take many deiferent characters from a string and replace them with one character
BTables
@lidya_q In that case, the answer is no, there is no built in function to do what you're asking.