Cyanic Wolf
Cyanic Wolf

Reputation: 69

Counting the words in a rich textbox in c# What am I doing wrong?

I would like to constantly update and show the number of words that I have in the rich textbox to be shown in the toolstrip. How can I achieve that please? It is not giving me an error, I would just like for where I have the toolstrip status label to be changed and show the word count but nothing is happening

namespace Calc
{
    public partial class Word_Count : Form
    {
        public Word_Count()
        {
            InitializeComponent();

            int count = 0;
            string wordcount = rtbCount.Text;
            foreach (char c in wordcount)
            {
                if (char.IsLetter(c))
                {
                    count++;                   
                }

                toolStripStatusLabel1.Text = count.ToString();
            }
        }
    }

}

Upvotes: 1

Views: 2367

Answers (2)

user13028588
user13028588

Reputation:

Another approach could be:

 MatchCollection wordCount = Regex.Matches(main_richTextBox.Text, @"[\W]+");

https://social.msdn.microsoft.com/Forums/en-US/81e438ed-9d35-47d7-a800-1fabab0f3d52/c-how-to-add-a-word-counter-to-a-richtextbox?forum=csharplanguage

    private void main_richTextBox_TextChanged(object sender, EventArgs e)
    {
        MatchCollection wordCount = Regex.Matches(main_richTextBox.Text, @"[\W]+");
        words_count_label.Text = wordCount.Count.ToString();

    }

The @myburthname's aproach did not count all of the words after doing enter, not sure why.

Upvotes: 0

mybirthname
mybirthname

Reputation: 18127

Here you will take all the words from the text box.

int count = rtbCount.Text.Split(' ').Count();

You can do it with Length property too, instead of Count method.

Upvotes: 2

Related Questions