Mike Patel

Mike Patel

  • NA
  • 7
  • 6.2k

String

Nov 20 2011 5:36 PM
Hello,

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();


    }


}




Answers (4)