开发者

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

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 stri开发者_运维百科ng2 will be the sub-set of string1 .. (i mean string1 will contain string2)..


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


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.


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.


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)


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;
}**
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜