2013-04-10 63 views
2

我正在努力查找一個字符串中子字符串的位置數。 以下代碼僅爲我提供了字符串中子字符串的起始位置。 請幫幫我。如何在C++中查找字符串中的子字符串的發生次數和位置

void Search(std::string SubString, vector<string> index) 
{ 
    vector<string>::const_iterator cii; 
    string temp; 
    bool found = false; 
    unsigned find = 0; 
    for(cii = index.begin(); cii != index.end(); cii++) 
    { 
     temp = *cii; 
     find = temp.find(SubString); 
     if(find != std::string::npos)//running.find() 
     { 
      cout << find << endl; 
      cout << *cii << endl; 
      found = true; 
     } 
     else 
     { 
      if((cii == index.end()) && found) 
      { 
       cout << "Not found\n"; 
       found = false; 
      } 
     } 
    } 
} 

int main() 
{ 
    vector<string> index; 
    ifstream myReadFile; 
    string str, running; 
    myReadFile.open("example.txt"); 
    char output[100]; 
    if (myReadFile.is_open()) 
    { 
     while (!myReadFile.eof()) 
     { 
      while(std::getline(myReadFile, str)) 
      { 

       index.push_back(str); 
      } 
     } 
    } 

    while(running != "END") 
    { 
     cout << "To Quit type:- END\n"; 
     cin >> running; 
     if(running == "END") 
     {break;} 
     else 
     { 
      Search(running, index); 
     } 

    } 

    myReadFile.close(); 
    return 0; 
} 

回答

2

看一看std::string::find reference。 Find有第二個參數,搜索開始的位置。因此,只要將查找作爲第二個參數放到循環中,直到查找返回std :: string :: npos。沿線的東西:

int startpos = 0; 
int finds = 0; 
while ((startpos = yourstring.find(substring, startpos)) != std::string::npos) 
    ++finds; 
+0

: - 感謝您的解決方案。我做的。請找到我更新的答案。 – 2013-04-10 13:08:33

+0

你需要在每次迭代時增加startpos,否則它會繼續爲startpos返回相同的輸出。 – Ajit 2014-06-04 14:00:23

0

最後我做到了。 我對Search()函數做了些許修改。 找到下面的代碼。

void Search(std::string SubString, vector<string> index) 
{ 
    vector<string>::const_iterator cii; 
    string temp; 
    bool found = false; 
    unsigned find = 0; 
    static int n = 0; 
    for(cii = index.begin(); cii != index.end(); cii++) 
    { 
     temp = *cii; 
     std::string ::size_type pos = 0; 
     while((pos = temp.find(SubString, pos)) 
       != std::string::npos) 
     { 
      n++; 
      pos += SubString.size(); 
      cout << pos << " "; 
     } 
     if(n) 
     { 
     cout << " \n "; 
     cout << *cii << endl; 
     found = true; 
     } 
     else 
     { 
      if((cii == index.end() - 1) && !found) 
      { 
       cout << "Not found\n"; 
       found = false; 
      } 
     } 
     n = 0; 
    } 

} 
+0

如果您的SubString包含自身(部分),您的代碼將無法按預期工作。例如:temp =「abababa」; SubString =「aba」;在temp中有3次SubString,但是你的代碼只能找到2,因爲你用'pos + = SubString.size()'跳過了第二個的開頭。這可能是故意的,只是想讓你知道。 – DaClown 2013-04-10 16:36:21

+0

@DaClown: - 感謝您指出錯誤。當然,我會看看同樣的。 – 2013-04-10 17:19:38

相關問題