简体   繁体   English

从文本中删除全部3个相同的词

[英]Delete 3 identical words from a text not all

I want to delete 3 words called "apple" from a string of textbox. 我想从文本框中删除3个单词,称为"apple" Textbox contain more than 3 apple words. 文本框包含超过 3分苹果的话。 I need to select only 3 to delete. 需要选择3个即可删除。

I used this code but it delete all apple words from the string. 我使用了这段代码,但是它删除了字符串中的所有苹果单词。

private void button4_Click(object sender, EventArgs e)
{
    textBox3.Text = textBox3.Text.Replace("apple","");
}

I want to delete 3 words only. 我只想删除3个字。 Do you have any idea how to achieve this? 你有什么想法要实现吗?

请看图片

You could use the overload of Regex.Replace to specify the maximum number of times to replace 您可以使用Regex.Replace的重载来指定要替换的最大次数

var regex = new Regex("apple");
var newText = regex.Replace(textBox3.Text, "", 3);

Yet another possibility is to Split (treating "apple" as a separator ) and Concat back: 还有一种可能是Split (将"apple"作为分隔符 )和Concat退回:

// 3 + 1: we want 3 separators to be eliminated, and thus 4 = 3 + 1 parts 
textBox3.Text = string.Concat(textBox3.Text
  .Split(new string[] { "apple" }, 3 + 1, StringSplitOptions.None));

You could try to look for the word "apple" three times (or less if it doesn't appear three times) in your string and to remove it from your current string. 您可以尝试在字符串中查找“苹果”一词三遍(如果未出现三遍,则少一些),并将其从当前字符串中删除。

private void button4_Click(object sender, EventArgs e)
{
    const string stringToRemove = "apple";

    int i = 0;
    int index = 0;
    string textBoxString = textBox3.Text;

    while(i<3 && index >= 0)
    {
        index = textBoxString.IndexOf(stringToRemove);

        textBoxString = (index < 0)? textBoxString : textBoxString.Remove(index, stringToRemove.Length);
        i++;
    }

    textBox3.Text = textBoxString;
}

There`s multiple way to accomplish what you want. 有多种方法可以完成您想要的。 1 of is is using regex, and 1 of is as sample below, basically loop and replace on how many time u want it to be. 1的使用正则表达式,1的作为下面的示例,基本上循环并替换您希望的时间。

string value = textBox3.Text;
for(int a = 0; a < 2;a++){
value = value.replace("apple","");
}

textBox3.Text=value;

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

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