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

时间:2019-02-14 19:23:50

标签: c#

我想制作一个程序,该程序以RichTextBox中的单词“ Me”为例。这在c#中怎么可能。我已经拥有的代码是它加载了一个文本文件。

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)
{

}

2 个答案:

答案 0 :(得分:2)

如果您想使用LINQ,则可以轻松完成。只需在空白处分割文本,然后过滤数组以查找与所需单词匹配的单词。这是一个示例:

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

答案 1 :(得分:0)

将所有单词分开,然后您就可以做任何想要的事情

//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(data[i].ToUpper() == stringToCompare.ToUpper() )
      n++;