2013-03-29 143 views
0

我想创建将通过句子的程序,如果它找到一个字符或一个字,它会显示它。C++搜索字符串

想象一下,只要找到第一个字符/字就停下来的程序。

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

你不需要循环。只要做到:

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"结果的live example

+0

是的,但它不会经历整个句子。例如。如果我尝试搜索字符“e”,它会在第9个位置找到它。 –

+0

@ user2114862:哦,所以你想查找所有的事件? –

+0

是的,所以它应该找到字符“e”3次并显示位置。 –