S
S
StrapusCactus2017-09-18 16:40:01
C++ / C#
StrapusCactus, 2017-09-18 16:40:01

How to count the number of matching characters in both strings?

How to count the number of characters that are in both the first and second line?
My decision:

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <clocale>
#include <string>
using namespace std;

int main()
{
    setlocale(LC_CTYPE, "rus");
    string a = "1234";
    string b = "9321";
    int p = 0;
    for(int z = 0; z < 4; z++){
        if(a.find(b[z]) == 0){
            p += 1;
        }
    }
    cout << p << endl;
    return 0;
}

According to the idea in the example, I need to get 2. Like the numbers 1 and 2 are in another line.
And the idea itself is as follows:
1. There is a line;
2. Walk along the line;
3. Calculate and add the number of matches to the variable
line 1234 = 1234 is equal to 4
line 1239 = 5912 is equal to 3
line 9876 = 6123 is equal to 1
I hope I described the problem well =)
Thanks for the help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
devalone, 2017-09-18
@StrapusCactus

#include <algorithm>
#include <iostream>
#include <set>
#include <string>

int main()
{
    std::string str1 = "just string with some numbers 124632";
    std::string str2 = "1234567890 i";
    std::set<std::string::value_type> setOfSymbolsInStr1(
        str1.begin(),
        str1.end());

    std::set<std::string::value_type> setOfSymbolsInStr2(
        str2.begin(),
        str2.end());

    std::set<std::string::value_type> intersection;
    std::set_intersection(
        setOfSymbolsInStr1.begin(),
        setOfSymbolsInStr1.end(),
        setOfSymbolsInStr2.begin(),
        setOfSymbolsInStr2.end(),
        std::inserter(intersection, intersection.begin()));

    std::cout << intersection.size() << std::endl;

    return 0;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question