Click here to Skip to main content
15,890,282 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
For example, there is two string:
string str1 = "abcde";
string str2 = "abccc";

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)
{
....
}

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, the Questioner very very contempt my answer:(
Posted
Updated 11-May-10 23:45pm
v2

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.
 
Share this answer
 
Comments
andersonhwang 12-May-10 6:21am    
Hi, John
Do you mean this:
public static int FindCommonChars(string str1, string str2)
{
Hashtable hTable = new Hashtable();
int i = 0;
foreach (char c in str1)
{
if (!hTable.Contains(c))
{
hTable.Add(c, c);
}
}
foreach (char c in str2)
{
try
{
hTable.Add(c, c);
}
catch (Exception ex)
{
i++;
continue;
}
}
return i;
}
but it will return 5, not 8.
C#
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;
    }

:-)
 
Share this answer
 
Comments
andersonhwang 12-May-10 21:24pm    
:DThis is good!
My senior show me one function that is:
C#
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());
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900