Search code examples
c++searchfor-loopwords

C++ search for words string


I want to create program which will go through sentence and if it finds a character or a word it will display it.

Think of a program that stops as soon as it find first character/word.

   string test("This is sentense i would like to find ! "); //his is sentense to be searched
   string look; // word/char that i want to search

   cin >> look;

   for (i = 0; i < test.size(); i++) //i<string size
    {
       unsigned searcher = test.find((look));
       if (searcher != string::npos) {
           cout << "found at : " << searcher;
       }
   }

Solution

  • You do not need the loop. Just do:

    std::cin >> look;
    std::string::size_type pos = test.find(look);
    while (pos != std::string::npos)
    {
        // Found!
        std::cout << "found at : " << pos << std::endl;
        pos = test.find(look, pos + 1);
    }
    

    Here is a live example showing the result for the input string "is".