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

时光总嘲笑我的痴心妄想 提交于 2019-12-01 17:46:08
Sumeet

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.

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;
});

you would probably rather want to try

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

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

string1.Replace(string2, "");

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

hhravn

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)

shiv kumar agarwal

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;
}**
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!