0

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

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

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

1 回答 1

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

这是一个显示输入字符串结果的实时示例"is"

于 2013-03-29T10:53:22.567 回答