c#在richtextbox中按顺序查找单词

时间:2014-12-16 07:23:20

标签: c# richtextbox

我有2 rich text boxes。第一个文本框包含输入,第二个文本框将显示找到的单词的输出

输入: 我的名字是umer 我父亲的名字是waqar

输出:

umer is found
my is found
name is found
is is found
father is found
my is found

输出不是我想要的。 我想要一个如下所示的输出

my is found
name is found
is is found
umer is found
my is found
father is found
name is found
is is found
waqar is found

我的代码是:

 private void button1_Click(object sender, EventArgs e)
        {
           if (richTextBox1.Text.Contains("umer"))
            richTextBox2.AppendText("\numer is found");

            if (richTextBox1.Text.Contains("my"))
            richTextBox2.AppendText("\nmy is found");

            if (richTextBox1.Text.Contains("name"))
            richTextBox2.AppendText("\nname is found");

            if (richTextBox1.Text.Contains("is"))
            richTextBox2.AppendText("\nis is found");

            if (richTextBox1.Text.Contains("father"))
                richTextBox2.AppendText("\nfather is found");

            if (richTextBox1.Text.Contains("waqar"))
                richTextBox2.AppendText("\nwaqar is found");
        }

3 个答案:

答案 0 :(得分:2)

如果您希望在每个字词之后is found,则可以将if列表替换为:

var words = richTextBox1.Text.Split(' ');
richTextBox2.Text = String.Join(words, " is found \n");

答案 1 :(得分:0)

你可以使用linq来获得独特的单词:

string text = "my name is umer my father name is waqar";

var uniqueWords = text.Split(' ').GroupBy(x => x).Select(x=>x.Key);

foreach (var value in uniqueWords)
{
   richTextBox2.AppendText(value +" is found");
}

<击>

更新(因为OP要求不是无用的词):

var result= text.Split(' ');

foreach (var value in result)
{
   richTextBox2.AppendText(value +" is found");
}

答案 2 :(得分:0)

这就是你所需要的:

 string[] words = richTextBox1.Text.Split(' ');       
 foreach (string searchString in words)
 {
      if (richTextBox1.Text.Contains(searchString))
      {
         richTextBox2.AppendText(searchString + " is found.\n");
      }
 }