C#: How to Delete the matching substring between 2 strings?

InfantPro'Aravind' picture InfantPro'Aravind' · Dec 10, 2009 · Viewed 18.9k times · Source

If I have two strings .. say

string1="Hello Dear c'Lint"

and

string2="Dear"

.. I want to Compare the strings first and delete the matching substring ..
the result of the above string pairs is:

"Hello  c'Lint"

(i.e, two spaces between "Hello" and "c'Lint")

for simplicity, we'll assume that string2 will be the sub-set of string1 .. (i mean string1 will contain string2)..

Answer

Paolo Tedesco picture Paolo Tedesco · Dec 10, 2009

What about

string result = string1.Replace(string2,"");

EDIT: I saw your updated question too late :)
An alternative solution to replace only the first occurrence using Regex.Replace, just for curiosity:

string s1 = "Hello dear Alice and dear Bob.";
string s2 = "dear";
bool first = true;
string s3 = Regex.Replace(s1, s2, (m) => {
    if (first) {
        first = false;
        return "";
    }
    return s2;
});