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 
bcontains character inathat's inc, you'll repeat it. - to avoid repeats, might consider using 
setstore characters, sincesetwon't have repeats. - assembling strings 
+=concatenation inefficient; consider usingstringbuilderor analogous string-assembly class. - your variable names aren't descriptive.
 - if 
aorbempty, 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
Post a Comment