2017-02-14 67 views
-2

我是編程新手,所以如果我的問題難以理解,我很抱歉。如何比較顯示差異數的字符串

我有一個字符串modelAnswer這樣

string modelAnswer = "ABABACDA"; 

所以它應該是問題的答案,我試圖讓這個如果用戶的輸入是 string studentAnswer = "ABADBDBB";例如程序將顯示我已經獲得了3分,因爲studentAnswer字符串的前三個字母與modelAnswer匹配。

+0

迭代通過串並比較每個元素。 – NathanOliver

+0

你可以比較兩個char字符。 –

+0

你可以在循環中使用[std :: mismatch](http://en.cppreference.com/w/cpp/algorithm/mismatch),直到它返回結束迭代器,找到差異集合。 –

回答

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; 
} 
+0

如果學生沒有給出足夠的答案,會發生什麼?你不計算那些空白。 – NathanOliver

+2

我不清楚爲什麼在這裏使用'stringstream'是一個優點。 –

2

可以使用標準算法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; 
} 

程序輸出是

3 

假設琴絃具有相同的長度。否則,你應該使用較少的字符串作爲第一對參數。

例如

#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'和lambda,但這樣好多了。 –

+0

@PeteBecker計數算法家族的常用替代方法是std :: accumulate和std :: inner_product。:) –

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. 
+0

你是對的,我已經更新了我的答案。謝謝! – Trevor