How to get the number of characters that two strings have in common in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        string str1 = "abcdefg";
        string str2 = "xayzgoe";

        int count = CommonCharactersCount(str1, str2);
        
        Console.WriteLine(count); 
    }

    static int CommonCharactersCount(string str1, string str2)
    {
        // Convert strings to sets of characters
        HashSet<char> set1 = new HashSet<char>(str1);
        HashSet<char> set2 = new HashSet<char>(str2);

        // Find the intersection
        set1.IntersectWith(set2);

        return set1.Count;
    }
}



/*
run:

3

*/

 



answered Mar 20, 2025 by avibootz
...