Please help explaining this code

I have some code here that someone else on this site wrote for me, and i was wondering some things about it.

CODE:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string input;

    getline (cin, input);

    string wordToFind("shit");
    string newWord ("****");

    size_t pos;

    pos = input.find(wordToFind);

    if (pos == string::npos)
    {
        cout << "" << endl;

    }
    else
    {

        input.replace(input.begin()+ pos + wordToFind.size(), newWord) ;
        cout << input << endl;
    }


}



Ok so my first question is what does .begin() do?? I watched a tutorial that covered .find, .replace and .erase but not .begin. Please just give me a plain english answer like, it does this, Please dont give me a technical answer like this: size_t is basically an unsigned integer. It's a typedef. Ok, but what does it do? and that is also my question, what is size_t?

Also this entire line is a bit confusing:

 
input.replace(input.begin()+ pos + wordToFind.size(), newWord) ;


In general having the entire thing explained would help me immensly. Thanks for the help. :)
what does .begin() do??


The string function begin returns an iterator object that refers to the first character in the string.
http://www.cplusplus.com/reference/string/string/begin/

size_t is an integer that goes from 0 to at least the largest number of bytes your computer can hold. On a 32-bit computer, this value may be ~4 billion.

-Albatross
Last edited on
input.replace(input.begin()+ pos + wordToFind.size(), newWord); does not compile.
Check out the correct version http://cplusplus.com/reference/string/string/replace/

In pos you've got the index of the first ocurrence of the substring.
@ch1156
Mate, If you are going to repeat what someone wrote, then at least get it right


This is what I wrote...


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 string input;

    getline (cin, input);

    string wordToFind("shit");
    string newWord ("crap");
    
    size_t pos;

    pos = input.find(wordToFind);

    if (pos == string::npos)
    {
        cout << "** Error - Search string not found in input **" << endl;

    }
    else
    {

        input.replace(input.begin()+pos, input.begin()+ pos+ wordToFind.size(), newWord) ;
        cout << input << endl;
    }
Last edited on
You could just input.replace(pos, wordToFind.size(), newWord);
Topic archived. No new replies allowed.