C ++搜索单词字符串

时间:2013-03-29 10:50:08

标签: c++ search for-loop words

我想创建将通过句子的程序,如果找到一个字符或一个单词,它将显示它。

想想一个程序在找到第一个字符/单词后立即停止。

   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;
       }
   }

1 个答案:

答案 0 :(得分:1)

您不需要循环。只是做:

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);
}

以下是live example,显示输入字符串"is"的结果。