-->

How can i ignore replace text within specific two

2019-09-13 11:17发布

问题:

I used following code snippet to replace text

private void textBox1_TextChanged(object sender, EventArgs e)
    {
        string A = textBox1.Text.Trim();
        string B = textBox1.Text.Trim();

        A = A.Replace("AB", "CD");
        A = A.Replace("GF", "HI");
        A = A.Replace("AC", "QW");
        A = A.Replace("VB", "GG");

        textBox2.Text = (A);

    }

but i wants to ignore this replace technique within || these symbol.As a example my code do this

when i type AB GF in a txtbox1,txtbox2 replace as following CD HI. Now i need when i type |AB GF| in txtbox1 ,txtbox2 replace as AB GF

i used this code to do this

textBox2.Text = ((B.Contains("|")) ? B.Replace("|", "") : A);

but this isn't work,after | this symbol all containing things in txtbox1 not replaced,how can i do this

回答1:

Per your comments, you will want to split your string on the spaces prior to doing the replacement. Afterwards you will join it all back together. This is pretty easy with Linq.

public Main()
{
    var strings = new string[]{ "AB GF", "|AB| GF" };
    foreach (var s in strings)
        Console.WriteLine(String.Join(" ", s.Split(' ').Select(x => ReplaceText(x))));
}

string ReplaceText(string text)
{
    if (text.Contains("|"))
        return text.Replace("|", String.Empty);
    else
    {
        text = text.Replace("AB", "CD");
        text = text.Replace("GF", "HI");
        text = text.Replace("AC", "QW");
        return text.Replace("VB", "GG");
    }
}

Prints:

CD HI

AB HI

Looking at your code. If you need to avoid a ReplaceText method. Something like this would work.

string A = textBox1.Text.Trim();

var subStrings = A.Split(' ');
for (int i = 0; i < subStrings.Count(); i++)
{
    if (subStrings[i].Contains("|"))
        subStrings[i] = subStrings[i].Replace("|", String.Empty);
    else
    {
        subStrings[i] = subStrings[i].Replace("AB", "CD");
        subStrings[i] = subStrings[i].Replace("GF", "HI");
        subStrings[i] = subStrings[i].Replace("AC", "QW");
        subStrings[i] = subStrings[i].Replace("VB", "GG");
    }
}

textBox2.Text = String.Join(" ", subStrings);