Confusion involving a while loop

So I'm having trouble grasping what the while loop is doing in this function. The output is supposed to be: d_mey _cdomefa_e. I realize that the function is originally looking for the first index that contains the character "o" and replacing it with "_", but, I'm not sure about the rest. I didn't know that str.find() could take on two parameters, either. Any help is appreciated!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <string>
#include <iostream>
using namespace std;
int main()
{
    string name = "domey mcdomeface";
    int i = name.find("o");
    while (i != string::npos) {
        name[i] = '_';
        ++i;
        i = name.find(name[i], i+1);
    }
    cout << name << endl;
}
Last edited on
Best to start from your last question first. str.find(s,p) looks for s, starting from index p (rather than the start) - see:
http://www.cplusplus.com/reference/string/string/find/

Here, your program starts by looking for an "o", replaces it with '_', moves on a letter (the ++i statement) to 'm'. Then it will try to find a subsequent 'm' starting at the next position (the i+1 on line 11), and replace it with '_'. And so on.

It basically keeps looking for a letter, replaces it with underscore, then repeats, but looking for the letter which follows that replaced. Here, this will give the sequence 'o', 'm', 'c', which are replaced in turn by underscore '_'. The while loop stops when the searched-for letter is not found in any remaining string (indicated by find returning string::npos).
Last edited on
Topic archived. No new replies allowed.