How to get only similar words that exist in two strings in C#

1 Answer

0 votes
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        string s1 = "c# c++ java php javascript";
        string s2 = "c python c++ c# java node.js";

        var matches = GetCommonWords(s1, s2);

        foreach (var word in matches) {
            Console.WriteLine(word);
        }
    }

    static string[] GetCommonWords(string a, string b)
    {
        string[] words1 = a.Split(" ", StringSplitOptions.RemoveEmptyEntries);
        string[] words2 = b.Split(" ", StringSplitOptions.RemoveEmptyEntries);

        return words1.Intersect(words2).ToArray();
    }
}



/*
run:

c#
c++
java

*/

 



answered Feb 10, 2022 by avibootz
edited May 25 by avibootz
...