Write a function that compares two strings and returns a third string containing only the letters that appear in both
.net, algorithm, c#, data-structures
Solution
That's fine for a first approach, but you can make a few improvements, and there's a small error.
- If `b` contains a character in `a` that's already in `c`, you'll repeat it.
- To avoid repeats, you might consider using a `Set` to store the characters, since a `Set` won't have repeats.
- Assembling strings with `+=` concatenation is usually inefficient; consider using a `StringBuilder` or an analogous string-assembly class.
- Your variable names aren't very descriptive.
- If `a` or `b` are empty, you don't have to do any work at all! Just return an empty string.
You can think about some more sophisticated improvements, too, by imagining how your algorithm scales if you started to use huge strings. For example, one approach might be that if one string is much longer than the other, you can sort the longer one and remove duplicates. Then you can do a binary search on the characters of the shorter string very quickly.
Problem
I got this homework. And have solved it in following way. I need your comments whether it is a good approach or I need to use any other data sturcture to solve it 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(); } ```