How to find common words in two strings with C#

1 Answer

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

class CommonWordsProgram
{
    /*
        Normalize a string:
        - Convert letters to lowercase
        - Replace any non-letter with a space
        This ensures consistent word comparison.
    */
    static string Normalize(string input)
    {
        var sb = new StringBuilder(input.Length);

        foreach (char ch in input) {
            if (char.IsLetter(ch))
                sb.Append(char.ToLower(ch));
            else
                sb.Append(' ');
        }

        return sb.ToString();
    }

    /*
        Extract words from a string.

        This function:
        - Normalizes the input
        - Splits on whitespace
        - Filters out empty entries
        - Returns a HashSet<string> for fast lookup and automatic duplicate removal
    */
    static HashSet<string> ExtractWords(string input)
    {
        string normalized = Normalize(input);
        string[] parts = normalized.Split(' ', StringSplitOptions.RemoveEmptyEntries);

        var words = new HashSet<string>(StringComparer.Ordinal);
        foreach (string w in parts)
            words.Add(w);

        return words;
    }

    /*
        Find common words between two strings.

        This function:
        - Extracts words from both strings
        - Uses set intersection for efficiency
        - Returns a new HashSet<string> containing the common words
    */
    static HashSet<string> FindCommonWords(string a, string b)
    {
        var wordsA = ExtractWords(a);
        var wordsB = ExtractWords(b);

        var common = new HashSet<string>(wordsA, StringComparer.Ordinal);
        common.IntersectWith(wordsB);

        return common;
    }

    static void Main()
    {
        string s1 = "The quick brown fox jumps over the lazy dog.";
        string s2 = "A lazy dog sleeps while the quick fox runs away.";

        var common = FindCommonWords(s1, s2);

        Console.WriteLine("Common words:");
        foreach (string w in common)
            Console.WriteLine(w);
    }
}


/*
run:

Common words:
the
quick
fox
lazy
dog

*/

 



answered Sep 11 by avibootz
...