从两个字符串中查找常见字符. [英] Find common char(s) from two string.

查看:88
本文介绍了从两个字符串中查找常见字符.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


例如,有两个字符串:

Hi,
For example, there is two string:

string str1 = "abcde";
string str2 = "abccc";


常见的字符是:
来自str1的a,b,c和来自str2的a,b,c,c,c.
因此,这些常见字符的总和为3 + 5 =8.
有人可以告诉我一个可以做到这一点的功能吗?


The common chars are:
a, b, c from str1, and a, b, c, c, c from str2.
So, the sum of these common char(s) is 3 + 5 = 8.
Could someone show me a function that can do this?

public int FindCommonChars(string str1, string str2)
{
....
}


我已经编写了一个2x嵌套循环,但是看起来非常...(您知道)
/*


I have written one 2x nested loop, but it seems very ... (you know)
/*

int i = 0;
foreach(char c1 in str1)
{
foreach(char c2 in str 2)
{
if(c1 == c2) i++;
}
}
foreach (char c2 in str 2)
{
foreach(char c1 in str1)
{
if(c2 == c1) i++;
}
}
return i;


*/
T_T,发问者非常鄙视我的答案:(


*/
T_T, the Questioner very very contempt my answer:(

推荐答案

使用包含字符串1中唯一字符的哈希表,然后只需要尝试从中添加字符字符串2并计算获得异常的次数(尝试添加哈希表中已存在的项目时发生).

这是我想到的第一个方法.您也可以使用Linq或regex.

您甚至可以将其减少到一个循环.
Use a hashtable that contains the unique characters from string 1, and then you only need to try adding characters from string 2 and count the number of times you get an exception (happens when you try to add an item that already exists in the hashtable).

That''s the first way I thought of. You could also probably use Linq or regex.

You could even reduce it to just one loop.


static int common(string s1, string s2)
    {
        int count = 0;
        byte [] a = new byte[26];
        byte [] b  = new byte[26];
        foreach(char c in s1)
            a[c - 'a']++;
        foreach (char c in s2)
            b[c - 'a']++;
        for (int i = 0; i < 26; i++)
        {
            if (a[i] != 0 && b[i] != 0) count += a[i] + b[i];
        }
        return count;
    }


:-)


我的上司给我看了一个功能,即:
My senior show me one function that is:
char[] ch1 = str1.ToCharArray();
char[] ch2 = str2.ToCharArray();

var p1 = ch1.Except(ch2);
var p2 = ch2.Except(ch1);
int count=(ch1.Length-p1.Count())+ (ch2.Length-p2.Count());


这篇关于从两个字符串中查找常见字符.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆