2017-02-14 3 views
-2

プログラミングには新しいので、私の質問が分かりにくいのはごめんなさい。違いの数を示す文字列を比較する方法

、ユーザの入力は、例えば string studentAnswer = "ABADBDBB";であれば、プログラムが表示されますように、私は、このような

string modelAnswer = "ABABACDA"; 

として文字列modelAnswerがだから、クイズに答えて、私はそれを作るしようとしていることになっている

私はstudentAnswer文字列の最初の3文字が3つの点をmodelAnswerと一致させています。

+0

反復し、各要素を比較します。 – NathanOliver

+0

2つの文字列charをcharで比較できます。 –

+0

[std :: mismatch](http://en.cppreference.com/w/cpp/algorithm/mismatch)をループ内で使用して、終了イテレータを返すまで差異のセットを見つけることができます。 –

答えて

0

stringstreamを使用すると、一度に1文字ずつテンポラリ変数にプッシュし、ループ内の等価性をテストできます。

#include <iostream> 
#include <string> 
#include <sstream> 

int main() { 
    std::istringstream model("ABABACDA"); 
    std::istringstream student("ABADBDBB"); 
    int diff = 0; 
    char m, s; 

    while ((model >> m) && (student >> s)) 
     if (m != s) diff++; 

    std::cout << diff << std::endl; // 5 

    return 0; 
} 
+0

生徒が十分な回答を得られない場合はどうなりますか?あなたはそれらの空白を数えません。 – NathanOliver

+2

なぜ私は 'stringstream'を使うのが有利なのかは分かりません。 –

2

あなたは、プログラムの出力は、文字列が同じ長さを持っていることを想定している

3 

ある

#include <iostream> 
#include <string> 
#include <numeric> 
#include <functional> 

int main() 
{ 
    std::string modelAnswer("ABABACDA"); 
    std::string studentAnswer("ABADBDBB"); 

    auto n = std::inner_product(modelAnswer.begin(), modelAnswer.end(), 
           studentAnswer.begin(), size_t(0), 
           std::plus<size_t>(), std::equal_to<char>()); 

    std::cout << n << std::endl; 


    return 0; 
} 

例えばとしての標準的なアルゴリズムstd::inner_productを使用することができます。それ以外の場合は、引数の最初のペアとしてless文字列を使用する必要があります。

#include <iostream> 
#include <string> 
#include <numeric> 
#include <algorithm> 
#include <functional> 
#include <iterator> 

int main() 
{ 
    std::string modelAnswer("ABABACDA"); 
    std::string studentAnswer("ABADBDBB"); 

    auto n = std::inner_product(modelAnswer.begin(), 
           std::next(modelAnswer.begin(), std::min(modelAnswer.size(), studentAnswer.size())), 
           studentAnswer.begin(), size_t(0), 
           std::plus<size_t>(), std::equal_to<char>()); 

    std::cout << n << std::endl; 


    return 0; 
} 
+0

うわー、偉大な洞察力( 'std :: endl'の使用を除いて)。私は 'count_if'とラムダについて考えていましたが、これははるかに優れています。 –

+0

@PeteBeckerカウントアルゴリズムファミリの一般的な代替方法はstd :: accumulateとstd :: inner_productです。 –

1

のためにあなたは標準文字列を使用している場合は、適切には(主に#include <string>)を含んで、あなたはそれらを比較し、各文字を反復するループのための簡単なを書くことができます。

std::string answer = "ABABACDA"; 
std::string stringToCompare = "ABADBDBB"; 
int score = 0; 
for (unsigned int i = 0; (i < answer.size()) && (i < stringToCompare.size()); ++i) 
{ 
    if (answer[i] == stringToCompare[i]) 
    { 
    ++score; 
    } 
} 
printf("Compare string gets a score of %d.\n", score); 

上記のコードは、以下の結果の印刷、私の作品:文字列を介して

Compare string gets a score of 3. 
+0

正しいですか、私は自分の答えを更新しました。ありがとう! – Trevor

関連する問題