views:

462

answers:

7

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)..

+10  A: 

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;
});
Paolo Tedesco
that would bestring1 = string1.Replace(string2,"");:o)
hhravn
Ya it works .. thank you :)
infant programmer
+4  A: 
string1.Replace(string2, "");

Note that this will remove all occurences of string2 within string1.

Konamiman
ohk .. fine .. Then how to avoid that .. I mean, suppose, if I want to delete only the first occurrence of string2 then?
infant programmer
+5  A: 

you would probably rather want to try

string1 = string1.Replace(string2 + " ","");

Otherwise you will end up with 2 spaces in the middle.

astander
No I want that space :)
infant programmer
So you require the double space in the middle?
astander
But Your answer is valuable too .. so +
infant programmer
A: 

I am not great at them so I can't give an example but regular expresssions are a powerful way of manioulating strings so might be worth a look.

James :-)

m0gb0y74
+2  A: 

Off the top of my head, removing the first instance could be done like this

    var sourceString = "1234412232323";
    var removeThis = "23";

    var a = sourceString.IndexOf(removeThis);
    var b = string.Concat(sourceString.Substring(0, a), sourceString.Substring(a + removeThis.Length));

Please test before releasing :o)

hhravn
oh ! your code is more understandable .. thanx :)
infant programmer
A: 

Use Replace simply when using "" as a Replacement string.

Sumeet
+2  A: 

Do this only:

string string1 = textBox1.Text; string string2 = textBox2.Text;

        string string1_part1=string1.Substring(0, string1.IndexOf(string2));
        string string1_part2=string1.Substring(string1.IndexOf(string2)+string2.Length, string1.Length - (string1.IndexOf(string2)+string2.Length));

        string1 = string1_part1 + string1_part2;

Hope it helps. It will remove only first occurance.

Sumeet
(thumbs up) thanx .. weldone :)
infant programmer
ya it works .. good work ..
infant programmer