简体   繁体   English

c++ - 如何在两个字符串中找到公共字符的数量

[英]How to find the number of common characters in two strings c++

If string 1 and string 2 are equal sizes, how would we find the num of common characters and store into some int?如果字符串 1 和字符串 2 的大小相等,我们如何找到常见字符的数量并将其存储到某个 int 中?

For example:例如:

string A = "abcdabc"
string B = "cabzabc"

The common number of characters is 6 out of 7 (count duplicates).常见的字符数是 7 个中的 6 个(计数重复)。

so far I have:到目前为止我有:

int count = 0;

for(int I = 0; I < A.size(); I++)
{
    if(A[I] == B[I]
    {
       count++;
     }
}

but when I output count its = 0.但是当我输出 count 它 = 0 时。

EDIT: got it to work guys, something was wrong with my initialized string but now its fine!编辑:让它开始工作,我的初始化字符串有问题,但现在很好! Thanks.谢谢。

What you are currently counting is whether those two char arrays have same character on a certain index.您目前正在计算的是这两个 char 数组在某个索引上是否具有相同的字符。 This is obviously not what you wish for.这显然不是你想要的。 Some options: 1. create map and store number of occurrences of each letter, then compare afterwards 2. iterate trough one array, and for each character there, iterate trough complete other array and count occurrences 3. sort these arrays in alphabetical order and you'll see how many times each letter occurs in each of them一些选项: 1. 创建映射并存储每个字母的出现次数,然后进行比较 2. 遍历一个数组,对于那里的每个字符,遍历完整的其他数组并计算出现次数 3. 按字母顺序对这些数组进行排序,然后你将看到每个字母在每个字母中出现多少次

EDIT: Let's run trough your code:编辑:让我们运行您的代码:

I = 0; A[I] = 'a'; B[I] = 'c' //are they the same? count = 0
I = 1; A[I] = 'b'; B[I] = 'a' //are they the same? count = 0
I = 2; A[I] = 'c'; B[I] = 'b' //are they the same? count = 0
I = 3; A[I] = 'd'; B[I] = 'z' //are they the same? count = 0
I = 4; A[I] = 'a'; B[I] = 'a' //are they the same? count = 1
I = 5; A[I] = 'b'; B[I] = 'b' //are they the same? count = 2
I = 6; A[I] = 'c'; B[I] = 'c' //are they the same? count = 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM