首页 > 解决方案 > Finding matching letters in a string at same spots

问题描述

I need a code to compare two strings: word and ptw. Both strings only have one word, and are of equal length and same case. The code needs to check the first character of both words and see if they are same and it will do this untill the end of the word. Then it will output the amount of matching letters (I don't need to know the matching letters).

Example: If word is windows and ptw is winowes it should output 4 as w, i, n, and s match.

I have tried the following however it does not check the positions:


string matchingletters(string word, string ptw) {

    string result = "";
    sort(begin(word), end(word));
    sort(begin(ptw), end(ptw));
    std::string intersection;
    std::set_intersection(begin(word), end(word), begin(ptw), end(ptw),
        back_inserter(intersection));
    string mlr = to_string(intersection.length());
    result = mlr + result;
    cout << result << endl;
    return result;

}

The result this gives when word is kanton and ptw is balkon is 4. It counts k even though k is at 0 position in word and 3 position at ptw and thus they are not in the same postion and should not be counted.

标签: c++

解决方案


假设这两个单词的长度相同,并且由于您不在乎哪些字母匹配,您可以简单地迭代并计算匹配字符

unsigned matchingletters(const std::string& word, const std::string& ptw) {
    assert(word.size() == ptw.size());

    unsigned count{0};
    for (size_t i = 0; i < word.size(); ++i) {
        if(word[i] == ptw[i])
            count++;
    }

    return count;
}

推荐阅读