[Solved] Reaching the 3rd word in a string [duplicate]


The most straightforward way:

#include <iostream>
int main()
{
    //input string:
    std::string str = "w o r d 1\tw o r d2\tword3\tword4";
    int wordStartPosition = 0;//The start of each word in the string

    for( int i = 0; i < 2; i++ )//looking for the third one (start counting from 0)
        wordStartPosition = str.find_first_of( '\t', wordStartPosition + 1 );

    //Getting where our word ends:
    int wordEndPosition = str.find_first_of( '\t', wordStartPosition + 1 );
    //Getting the desired word and printing:
    std::string result =  str.substr( wordStartPosition + 1, str.length() - wordEndPosition - 1 );
    std::cout << result;
}

output:

word3

0

solved Reaching the 3rd word in a string [duplicate]