mzee99
mzee99

Reputation: 191

How to find a string of 2 words in a file?

With the following code, I can find a string of 1 word (in this example I'm looking for "Word"):

ifstream file("file.txt");
string str;
while (file >> str){
    if (str.find("Word") != string::npos){
         ////
    }
}

But it doesn't work if I want to find, for example, "Computer screen", which is composed of two words.

Thanks

Upvotes: 0

Views: 1307

Answers (2)

Keith
Keith

Reputation: 6834

If you know there are two words and what they are, all you need is this:

ifstream file("file.txt");
string str;
while (file >> str){
    if (str.find("Computer") != string::npos){
         file >> str;
         if (str.find("screen") != string::npos) {
         ////
         }         
    }
}

But more likely, you are asking to find a single string that might be two words, or three or more.

Then, can you count on the string being on a single line? In which case, @Ashalynd's solution will work. But if the string might be broken it will fail. You then need to handle that case.

If your file is "small" - i.e. can easily fit in memory, read in the whole thing, remove line breaks and search for the string.

If it is too large, read in lines as pairs.

Something like this:

std::ifstream file("file.txt");
std::string str[2];
int i = 0;
std::getline (file,str[i]);
++i;
while (std::getline (file,str[i]))
{
    int next_i = (i+1)%2;
    std::string pair = str[next_i] + " " + str[i];
    if (pair.find("Computer screen") != std::string::npos)
    {
        ////
    }
    i = next_i;
}

All this assumes that the possible white space between the words in the string is a single space or a newline. If there is a line break with more white-space of some kind (e.g. tabs, you need either to replace white-space in the search string with a regex for white-space, or implement a more complex state machine.

Also, consider whether you need to manage case, probably by converting all strings to lower case before the match.

Upvotes: 0

Ashalynd
Ashalynd

Reputation: 12563

file >> str reads a parameter (in this case, a string) delimited with whitespace. If you want to read the whole line (or in any case, more than one word at once), you can use getline operator (reads the string which is delimited by newline by default).

ifstream file("file.txt");
string str;
while (std::getline (file,str)){
    if (str.find("Computer screen") != string::npos){
         ////
    }
}

Upvotes: 2

Related Questions