Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 string2 will be the sub-set of string1 .. (i mean string1 will contain string2)..

like image 474
InfantPro'Aravind' Avatar asked Dec 10 '09 09:12

InfantPro'Aravind'


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.


2 Answers

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;
});
like image 196
Paolo Tedesco Avatar answered Oct 16 '22 05:10

Paolo Tedesco


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.

like image 41
Sumeet Avatar answered Oct 16 '22 05:10

Sumeet