Reputation: 200
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();
}
}
Upvotes: 1
Views: 1829
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
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
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