如何比较显示差异数量的字符串

时间:2017-02-14 14:56:48

标签: c++ string

我是编程新手,所以如果我的问题难以理解,我很抱歉。

我有一个字符串modelAnswer本身

string modelAnswer = "ABABACDA";

所以它应该是测验的答案,我试图让它成为如果用户的输入是 string studentAnswer = "ABADBDBB";例如,该程序将显示我得到3分,因为studentAnswer字符串的前三个字母与modelAnswer匹配。

3 个答案:

答案 0 :(得分:2)

您可以使用标准算法<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="map_outer" style="position: absolute; left: 3px; z-index: 1;"> <svg height="35" version="1.1" width="35" xmlns="http://www.w3.org/2000/svg" style="overflow: hidden; position: relative;"><desc style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);-moz-tap-highlight-color: rgba(0, 0, 0, 0);">Created with Raphaël 2.1.0</desc> <defs style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);-moz-tap-highlight-color: rgba(0, 0, 0, 0);"> </defs> <path fill="#cecece" stroke="#808080" d="M503.7,743.8C694,647.1999999999999,636.6,326.74999999999994,348.1,334.09V205.39L120.00000000000003,400.39L348.1,606.19V474.59000000000003C589,469.09000000000003,578,677.3900000000001,503.70000000000005,743.8900000000001Z" stroke-width="40" stroke-opacity="1" fill-opacity="1" transform="matrix(0.05,0,0,0.05,-1.9,-5.7)" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); stroke-opacity: 1; fill-opacity: 1; cursor: pointer;"> </path> </svg> </div>,例如

std::inner_product

程序输出

#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;
}

假设字符串具有相同的长度。否则,您应该使用less字符串作为第一对参数。

例如

3

答案 1 :(得分:1)

如果你使用标准字符串,使用正确的包含(主要是#include <string>),你可以编写一个简单的for循环来迭代每个字符,比较它们。

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.

答案 2 :(得分:0)

使用stringstream,您可以一次将一个字符推入临时变量并在循环中测试等效性。

#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;
}