c#在richtextbox中按顺序查找单词
我有两个c#在richtextbox中按顺序查找单词,c#,richtextbox,C#,Richtextbox,我有两个富文本框。第一个文本框包含输入,第二个文本框将显示找到的单词的输出 输入: 我叫乌默 我父亲叫瓦卡尔 输出: 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 fo
富文本框
。第一个文本框包含输入,第二个文本框将显示找到的单词的输出
输入:
我叫乌默
我父亲叫瓦卡尔
输出:
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");
}
您可以使用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要求不是uinque文字):
如果要在每个单词后找到
,可以将If
列表替换为:
var words = richTextBox1.Text.Split(' ');
richTextBox2.Text = String.Join(words, " is found \n");
这是您所需要的:
string[] words = richTextBox1.Text.Split(' ');
foreach (string searchString in words)
{
if (richTextBox1.Text.Contains(searchString))
{
richTextBox2.AppendText(searchString + " is found.\n");
}
}
我正在学习c#因此如果有人能给出简单而详细的解决方案,我将不胜感激。你基本上想要的是在每个单词后找到的吗?你的问题不清楚。你到底想对输入做什么?(您希望实现的看似随机的输出的规则是什么)我只是在学习按照输入中出现的顺序编写找到的单词(顺序与输入顺序相同)if(richTextBox1.Text.Contains(“waqar”))richTextBox2.AppendText(“\nmy is found”)代码>这没有意义。如果发现my包含waqar,为什么要追加my?可能是我无法解释我的内容:(我试图找到单词并将它们写在richtextbox2中。但我无法按顺序完成。是的,这正是我想要的。因为我想搜索整个段落,并在richtextbox2中显示搜索到的单词(如果它们存在于richtextbox1@UmerWaqar-您好,请参阅我编辑的答案。它提供您所需的输出。
string[] words = richTextBox1.Text.Split(' ');
foreach (string searchString in words)
{
if (richTextBox1.Text.Contains(searchString))
{
richTextBox2.AppendText(searchString + " is found.\n");
}
}