简体   繁体   中英

C++ string.find(' ')

The goal is to use the sentence.find('and') to find all of the positions of "ands" in the string. The int variable has to be used as well.

What I've done so far:

#include <iostream>
#include <string>

using namespace std;
int main() {

    string sentence;
    int first, second, third;
    sentence = "My name is Ryan and I like sports and music and movies";
    first = sentence.find('and');
    second = sentence.find('and');
    third = sentence.find('and');

    cout << "Position of first and is: " << first << endl;
    cout << "Position of second and is: " << second << endl;
    cout << "Position of third and is: " << third << endl;

    system("pause");
    return 0;

}

It only computes as 18 for all 3 ,but I need to find the position of each individual "and" . Please help,

Thanks in advance

The second (obviously optional) argument to find specifies where in the string to start searching from; use that to skip over the occurrences you have already found.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM