2016-12-10 119 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