Given the code below, how do reduce the code to only display the total count of lower case a and upper case A?
using
System;
using
System.Text;
class
Test
{
static void Main()
{
string input = " In this assignment, I need to count all occurence of lower cAse a and upper case A";
string output = CountAllChars(input);
Console.WriteLine(output);
Console.ReadLine();
}
static string CountAllChars(string s)
{
if (s == null) return null;
if (s == "") return "";
s = s.ToLower();
char[] chars = s.ToCharArray();
Array.Sort(chars);
StringBuilder sb = new StringBuilder();
int count = 0;
for (int i = 0; i < chars.Length; i++)
{
if (chars[i] < 'a' || chars[i] > 'z') continue;
if (sb.Length == 0)
{
sb = sb.Append(chars[i]);
count = 1;
}
else if (chars[i] == chars[i - 1])
{
count++;
}
else
{
sb = sb.Append(count.ToString());
sb = sb.Append(chars[i]);
count = 1;
}
}
sb = sb.Append(count.ToString());
return sb.ToString();
}
}

VulpesRank #55 · 29.2K reputationPosted Nov 20, 2011, 1:49 PM EST
All it really needs is this:
NarayanRank #8,477 · 221 reputationPosted Nov 20, 2011, 5:37 PM EST
using System.Text.RegularExpressions;
string input = "In this assignment, I need to count all occurrences of lower case a and upper case A";
Console.WriteLine("The number of a's is {0}", Regex.Matches(input,"a").Count);
Console.WriteLine("The number of A's is {0}", Regex.Matches(input, "A").Count);
}
}
Debata
VulpesRank #55 · 29.2K reputationPosted Nov 21, 2011, 2:08 AM EST
However, I used the 'traditional' approach in my first post as I thought it was unlikely that Mike would have covered regular expressions or LINQ yet in his studies.
Sam HobbsRank #107 · 20.5K reputationPosted Nov 21, 2011, 1:16 PM EST