c# - Write a function that compares two strings and returns a third string containing only the letters that appear in both -


i got homework. , have solved in following way. need comments whether approach or need use other data sturcture solve in better way.

    public string returncommon(string firststring, string scndstring)     {         stringbuilder newstb = new stringbuilder();         if (firststring != null && scndstring != null)         {             foreach (char ichar in firststring)             {                 if (!newstb.tostring().contains(ichar) && scndstring.contains(ichar))                     newstb.append(ichar);             }         }         return newstb.tostring();     } 

that's fine first approach, can make few improvements, , there's small error.

  • if b contains character in a that's in c, you'll repeat it.
  • to avoid repeats, might consider using set store characters, since set won't have repeats.
  • assembling strings += concatenation inefficient; consider using stringbuilder or analogous string-assembly class.
  • your variable names aren't descriptive.
  • if a or b empty, don't have work @ all! return empty string.

you can think more sophisticated improvements, too, imagining how algorithm scales if started use huge strings. example, 1 approach might if 1 string longer other, can sort longer 1 , remove duplicates. can binary search on characters of shorter string quickly.


Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -