Friday, 26 July 2013

Find no. of occurrence of each character in a string

 protected void btn_go_Click(object sender, EventArgs e)
    {
        ltrl.Text = "";
        CountAllCharacters(txt_name.Text);
    }
    protected void CountAllCharacters(string text)
    {
        text = text.ToUpper();
        for (int i = 0; i < text.Length; i++)
        {
            //don't count same char a second time
            if (text[i] != ' ' && (i == 0 || !text.Substring(0, i - 1).Contains(text[i])))
            {
                int count = CountCharacters(text[i], text);
               ltrl.Text+= string.Format("{0} occurs {1} {2}", text[i].ToString().ToLower(), count.ToString(), count > 1 ? "times" : "time");
               ltrl.Text += "<br/>";
            }
        }
    }

    protected int CountCharacters(char target, string text)
    {

        int returnVal = 0;

        for (int i = 0; i < text.Length; i++)
        {
            if (text[i].ToString().ToUpper() == target.ToString().ToUpper())
                returnVal++;
        }
        return returnVal;
    }

No comments:

Post a Comment