How to find all instances of a word in a string

Pages: 12
In your code there is no any need 1) to introduce new variable 't' of type string; 2) to declare it const. I did that because I set value of the string explicitly and only once.

As for your code you could write simply

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    cout << "Enter a line of text" << endl;
    getline(cin, enterText);

    cout << "What word do you want to find" << endl;
    cin >> find;

    size_t numberOfInstances = 0;

    string::size_type pos = 0;

    while((pos = enterText.find(find, pos)) != string::npos)
    {
        numberOfInstances++;
        pos += find.size();
    }


size_t is a standard typedef name as defined as

typedef unsigned int size_t;

It is simply to write size_t than unsigned int.

As for the loop you start seaching the string with pos 0 in the string. If target word is found you move the position in the string right after the found word that to search an other occurence of the word.

I would like also to note that it is a bad idea to name string as find because there are other entities in C++ that have name find as for example standard algorithm std::find.
Last edited on
Ok i see now, awesome. can you answer my other question by chance?

http://www.cplusplus.com/forum/beginner/82191/
Whats size_type?
It is a typedef for some fundamental type defined in std::string to represent a string length.
Oh i see, what about .str(); ? i read that it converts an integer value to a string, is that correct?
Topic archived. No new replies allowed.
Pages: 12