I am looking for a method that will take two strings and return the number of characters that are common to both e.g.:
"G010" & "G1820A" should return 3 as the G, 0 and 1 chars exist in both.
If a char exists twice in both they should be counted separately as follows:
"G12AA" & "GAA2" should return 4 as the G, A, A and 2 characters exist in both.
Any help with this? Google searches haven't been too helpful thus far.
Okay, how about this, it has the advantage of maximising lazy evaluation and minimising string manipulation.
essentialy, it groups each side by char, then finds chars which have a group on both sides. The matched groups are counted in tandem, until either runs out. These counts are summed to produce the result.
It would be trivial to perform this generically for any two sequences. See below,
Which you would use like this.
The optional
comparer
parameter may prove useful if you require case insensitivity or other special treatment.In the interest of resuability, I'd be tempted to remove the
Sum()
and return anIEnumerable<T>
, and then add sum to the call, like this,so you could easily do
or just the orgininal
This one would run faster with larger inputs as it doesn't do nesting loops but rather depends on hashed search using the Dictionary. On the other hand it uses more memory.
You could use Linq to solve this problem by using something like this:
commonChars will have a value of 3. The FindCommonElements method was inspired by this question: How do I do an integer list intersection while keeping duplicates?
check this out, btw not efficient. But got it right.
Please check following code--> src is first string while chk is second string