简体   繁体   English

我如何计算一个富文本框中的单词

[英]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. 我想制作一个程序,该程序可以将RichTextbox中的单词“ Me”作为示例。 How is this possible in c#. 这在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)
{

}

If you want to use LINQ, you can do it pretty easily. 如果要使用LINQ,则可以轻松完成。 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();

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++;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM