Text and data structures
C# uses UTF-16 internally, so a
char is actually 2 bytes long (and even then not all Unicode characters can be stored in a
char). An array of 256 (a single byte can have 256, not 255, different values) is not sufficient. A
Dictionary<char, int> would be more suitable here. For example, the following code is not limited to Latin characters, so feeding it some Cyrillic should work just fine:
var charCounts = new Dictionary<char, int>();
foreach (char c in s)
charCounts[c] = 1;
You said that you want to ignore space characters, but your code also ignores some control characters (but not all). You may want to use
char.GetUnicodeCategory to determine which characters should be counted (there are several categories: various kinds of letters, digits, control characters and so on).
As for returning multiple characters, that's what arrays and lists are for. Instead of appending characters to a string, add them to a list and return that list when you're finished.
- Don't use 'magic values' (such as that 255 that's appearing several times). When you iterate an array, use its
for (int i = 0; i < cc.Length; i++).
- Using a
char to index an array makes your code a little confusing to read. I don't see any advantages over using a 'standard'
- I would also not recommend reusing an indexing variable (
c): it's easy to introduce bugs by forgetting to 'reset' its value.
- You don't need to initialize an array of ints with 0's: C# already does that for you (0 is the default value for
- Try using meaningful variable names:
input instead of
charCounts or even
characterCounts instead of
cc, and so on. It'll make your code easier to understand, and that's a good thing when you have to revisit code a few months later.
- The easiest way to get the maximum value from a collection is to use Linq's
cc.Max(). There are also several other Linq methods that could make this method easier to write, such as