How to remove the letters from word1 if they do not exist in word2 with C#

1 Answer

0 votes
using System;

class Program
{
    static string RemoveNonCommonLetters(string word1, string word2) {
        string result = "";
        
        foreach (char c in word1) {
            if (word2.Contains(c)) {
                result += c;
            }
        }
        
        return result;
    }

    static void Main()
    {
        string word1 = "forest";
        string word2 = "tor";

        string result = RemoveNonCommonLetters(word1, word2);

        Console.WriteLine(result);
    }
}



/*
run:

ort

*/

 



answered Jul 9, 2025 by avibootz
...