Search code examples
c#toolstrip

Counting a character and display in toolStripStatusLabel


I want to count how much characters there are, every time I put text into a rich text box.

(If I type 'Hello there' (it should display "10 characters..." instead of "2 characters...")

private void rtbText_TextChanged(object sender, EventArgs e)
        {
            char[] arrCharacter = new char[1] { ' ' };
            int countChar = rtbText.Text.Split(arrCharacter).Length;

            char[] arrVowels = new char[5] { 'a', 'e', 'i', 'o', 'u' };
            int countVowels = rtbText.Text.Split(arrVowels).Length;

            toolStripStatusLabel1.Text = countChar + " characters, of which " + countVowels + " are vowels.";
        }

It surely has to do something with this line. As it is, it gives me WORD count not character.

char[] arrCharacter = new char[1] { ' ' };

Thanks for your help!


Solution

  • I think your code is overly complicated :)

    I would use something more like:

    var vowels = new char[]{ 'a', 'e', 'i', 'o', 'u' };
    var vowelCount = rtbText.Text.Count(c => vowels.Contains(c));
    var characterCount = rtbText.Text.Length;
    toolStripStatusLabel1.Text = characterCount + " characters, of which " 
        + vowelCount + " are vowels.";