user9771053
user9771053

Reputation:

How can i count the words from a richtextbox

I want to make a program that counts as example the word "Me" from a richtextbox. How is this possible in c#. The code that i already have is that it loads a textfile.

private void button1_Click(object sender, EventArgs e)
{
    Stream myStream;
    OpenFileDialog openFileDialog1 = new OpenFileDialog();

    if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        if ((myStream = openFileDialog1.OpenFile()) != null)
        {
            string strfilename = openFileDialog1.FileName;
            string filetext = File.ReadAllText(strfilename);
            richTextBox1.Text = filetext;
            textBox1.Text = openFileDialog1.FileName;
            richTextBox1.LoadFile(@"C:\Users\Administrator\Documents\School\C#\DEEL 2\HW5\5.3 opdracht1\Sonnet 14.txt", RichTextBoxStreamType.PlainText);
        }
    }
}

private void button2_Click(object sender, EventArgs e)
{

}

Upvotes: 0

Views: 94

Answers (2)

maxime bélair
maxime bélair

Reputation: 154

If you want to use LINQ, you can do it pretty easily. Simply split the text on whitespaces, and then filter the array for words matching what you want. Here's a sample:

string search = "Me";
int count = richTextBox1.Text.Split(' ').Where(word => word == search).Count();

Upvotes: 2

João Paulo Amorim
João Paulo Amorim

Reputation: 436

Separete all the words and after that you can do whatever you want

//Variable to store your count
int n = 0;
string stringToCompare = "Me";
string[] data = richTextBox1.Text.Split(' ');
for(int i=0;i<data.Length;i++)
{
  if(data[i]==stringToCompare )
     n++;
}
Console.WriteLine($"Word {stringToCompare } has appeared {n} times");

If you dont want case sensitive try something like

if(data[i].ToUpper() == stringToCompare.ToUpper() )
      n++;

Upvotes: 0

Related Questions