2013-03-29 139 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次並顯示位置。 –