2016-12-10 12 views
0

引数をファイル内のテキストと比較するプログラムで作業します(私のファイルは、多くの英語を含む辞書です)。2つの文字列を個別の文字で比較します。C++

現在、アプリケーションは完全に一致する文字列のみを処理します。

ファイル内の完全な文字列に入力された部分文字列を比較して一致させる方法があるかどうかを知りたがっていました。 例argがapの場合、apple、application alliance extに一致します。

# 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」のこと...それとGoogleの代わりにやるべきことはしないでください。 – 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)のような寓意によって類似性を探しているのでしょうか? [Googleにはリンクがあります](http://www.google.com/search?q=levenshtein+distance+c%2B%2B) – LotPings

答えて

3

「一致」とは、「ファイルからの文字列に入力からの文字列が含まれている」という場合は、string :: findメソッドを使用できます。この場合、あなたの条件は、次のようになります。

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

場合は、もう一度あなたが文字列を使用することができますし、「ファイルから文字列が入力から文字列で始まる」を意味する「一致」::見つけることではなくて以下の条件:

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

関連ドキュメントはhereです。文字列にargv[1]をコピーして

+0

ありがとうございました! –

0

スタートを(厳密には必要ではないが、それは、その後の比較ビット簡単になります):

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

次に使用std::equalequal

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

この形式を( C++で追加されました.14)は、2つのシーケンスのうち短いものが長いものの先頭にある対応する文字と一致する場合、trueを返します。