Jiachang  Yang
Jiachang Yang

Reputation: 200

Count the number of the same words in richtextbox

I want to count the words in richtextbox. First, i input a word in textbox1(for searching), and press "count" button, textbox2 will show a number about how many the same words in the richtextbox. Here are my codes, but it doesn't work, the textbox2 always shows 0.Thank you for your help.

      private void button2_Click(object sender, EventArgs e)
   {
     string a=richTextBox1.Text;
     string b=textBox1.Text;

     for (int i = 0; i < a.Length; i++)
     {

        int n=0;

        if (a.Equals(b))
        {

          n++;

        }

        textBox2.Text = n.ToString();

     }

  }

enter image description here

Upvotes: 1

Views: 1829

Answers (3)

VBlppc2
VBlppc2

Reputation: 1

It's a bit more easier to show word count for richtextbox like this:

Dim wordcount As Integer
Dim a As String() = RichTextBox1.Text.Split(" ")
wordcount = a.Length

You can use 'wordcount' for the word count. For example:

Label1.Text = "Word Count: " & wordcount

Upvotes: 0

roybalderama
roybalderama

Reputation: 1640

Try this one:

string data = richTextBox1.Text;
var target  = textBox1.Text;
var count = data.Select((c, i) => data.Substring(i))
                .Count(sub => sub.ToUpper()
                .StartsWith(target));

textBox2.Text = count;

Upvotes: 1

Tianyun Ling
Tianyun Ling

Reputation: 1097

You need to compare the individual word to b, not the whole sentence. You can use the following code as a reference:

string[] data = richTextBox1.Text.Split(' ');
for(int i=0;i<data.Length;i++)
{
   if(data[i]==textBox1.Text)
      n++;
}

Upvotes: 1

Related Questions