Friday, 13 December 2013

Find chare occurence in string

 protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnget_Click(object sender, EventArgs e)
    {
        CountAllCharacters(txtinput.Text,'a');
    }

    protected void CountAllCharacters(string text,char pattern)
    {
        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(pattern, text);
                lblresult.Text = pattern.ToString() + " Occures " + count + " Times";
                //lblresult.Text = string.Format("{0} occurs {1} {2}", pattern.ToString().ToLower(), count.ToString(), count > 1 ? "times" : "time");
            }
        }
    }
    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