How to find and print the common characters (letters) in different strings with C#

1 Answer

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

public class Program
{
    public static string GetCommonCharacters(string str1, string str2) {
        HashSet<char> commonChars = new HashSet<char>();
        foreach (char ch in str1) {
            if (ch != ' ' && str2.Contains(ch)) {
                commonChars.Add(ch);
            }
        }

        StringBuilder sb = new StringBuilder();
        foreach (char ch in commonChars) {
            sb.Append(ch);
        }

        return sb.ToString();
    }

    public static void Main(string[] args)
    {
        string str1 = "c c++ c# java go";
        string str2 = "python nodejs php javascript";

        string strcommon = GetCommonCharacters(str1, str2);

        Console.WriteLine("Same letters are: " + strcommon);
    }
}




/*
run:
   
Same letters are: cjavo
   
*/

 

 



answered Jan 26, 2024 by avibootz
...