9

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

Rookie Programmer Aravind
  • 11,952
  • 23
  • 81
  • 114

6 Answers6

14

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
  • 55,237
  • 33
  • 144
  • 193
9

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.

Konamiman
  • 49,681
  • 17
  • 108
  • 138
Sumeet
  • 905
  • 1
  • 14
  • 32
5

you would probably rather want to try

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

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

Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
4
string1.Replace(string2, "");

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

Konamiman
  • 49,681
  • 17
  • 108
  • 138
2

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)

Konamiman
  • 49,681
  • 17
  • 108
  • 138
hhravn
  • 1,701
  • 1
  • 10
  • 22
0

Try This One only one line code...

string str1 = tbline.Text;
string str2 = tbsubstr.Text;
if (tbline.Text == "" || tbsubstr.Text == "")
{
    MessageBox.Show("Please enter a line and also enter sunstring text in textboo");
}
else
{
    **string delresult = str1.Replace(str2, "");**
    tbresult.Text = delresult;
}**
Konamiman
  • 49,681
  • 17
  • 108
  • 138