Saturday, 16 November 2024

Coding Test : find common character between two string

 Try to find common character with it's count between two strings and display it console.

Input:  string1: Dotnet , string2: Hotstar

Output:  o - 1, t - 2

  string str1 = "Dotnet";
  string str2 = "Hotstar";

  List<char> lst1 = str1.ToList();
  List<char> lst2 = str2.ToList();
  Dictionary<char, int> commonCharsDic = new Dictionary<char, int>();

  foreach (char c in lst1)
  {
      if (lst2.Contains(c))
      {
          int val;
          if (commonCharsDic.TryGetValue(c, out val))
              commonCharsDic[c] = val + 1;
          else
              commonCharsDic.Add(c, 1);

          lst2.Remove(c);
      }
  }

  foreach (var item in commonCharsDic)
      Console.WriteLine("{0}-{1}", item.Key, item.Value);

 // Output: o-1 , t-2

below is another similar logic


  string str1 = "Dotnet";
  string str2 = "Hotstar";

  List<char> lst1 = str1.ToList();
  List<char> lst2 = str2.ToList();
 
  var res2 = lst1.Intersect(lst2).ToList();
  Dictionary<char, int> dict = new Dictionary<char, int>();

  foreach (var item in res2)
      dict.Add(item, 0);

  foreach (var item in lst1)
  {
      if (lst2.Contains(item))
          dict[item] = dict[item] + 1;

      lst2.Remove(item);
  }

  foreach (var item in dict)
      Console.WriteLine("{0}-{1}", item.Key, item.Value);

 // Output: o-1 , t-2


0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (55) CD (1) CI (2) CloudComputing (2) Coding (10) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (20) Entity Framework (5) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) jwtToken (4) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives