2016-12-10 26 views
0

處理將參數與文件中的文本進行比較的程序(我的文件是包含大量英語單詞的字典)。比較由單個字符的兩個字符串C++

現在應用程序只工作字符串完全匹配。

想知道是否有一種方法來比較輸入到文件中完整字符串的部分字符串,並將其匹配。 例如,如果參數是ap,它會匹配它到蘋果,應用程序聯盟分機。

# include <iostream> 
    # include <fstream> 
    # include <cstdlib> 
    # include <string> 
    using namespace std; 


    int main (int argc, char *argv[]) { 



      ifstream inFile; 
      inFile.open("/Users/mikelucci/Desktop/american-english-insane"); 

      //Check for error 

      if (inFile.fail()) { 
       cerr << "Fail to Open File" << endl; 
       exit(1); 
      } 

      string word; 
      int count = 0; 


      //Use loop to read through file until the end 

      while (!inFile.eof()) { 
       inFile >> word; 
       if (word == argv[1]) { 
        count++; 
       } 
      } 

      cout << count << " words matched." << endl; 

     inFile.close(); 
     return 0; 

    } 
+1

'ap'應該與'alliance'匹配嗎?然後只是比較第一個字符。否則,[這裏](http://stackoverflow.com/questions/1878001/how-do-i-check-if-ac-string-starts-with-a-certain-string-and-convert-a-sub)是你的副本。而這個'eof'的東西...不要這樣做,谷歌爲什麼/做什麼,而不是。 – LogicStuff

+0

std :: string :: compare()或std :: regex - 不要在eof()上循環 - 請參閱https://latedev.wordpress.com/2012/12/04/all-about-eof/爲什麼 –

+0

也許你正在通過像[lenshtein-distance](https://en.wikipedia.org/wiki/Levenshtein_distance)這樣的algorythm尋找相似之處? [Google有鏈接](http://www.google.com/search?q=levenshtein+distance+c%2B%2B) – LotPings

回答

3

如果通過「匹配」,你的意思是「從文件中的字符串包含輸入的字符串」,那麼你可以使用string :: find方法。在這種情況下,你的情況看起來像:

word.find(argv[1]) != string::npos 

如果「匹配」那麼你說「從文件中的字符串從輸入字符串開頭」,你可以再次使用string ::找到,但與以下條件:

word.find(argv[1]) == 0 

相關文檔是here

+0

非常感謝! –

0

開始複製argv[1]成字符串(不是絕對必要的,但它使後續比較簡單一點):

std::string target(arg[1]); 

然後使用std::equal

if (std::equal(word.begin(), word.end(), target.begin(). target.end())) 

這種形式的equal(如果兩個序列中較短的一個與較長的開始處的對應字符匹配,則返回true