C #: How to remove a matching substring between two lines?

If I have two lines. let's say

string1 = "Hello Dear c'Lint"

and

string2 = "Dear"

.. I want to compare the strings and remove the matching substring ..
result of the above pairs of lines: i>

"Hello c'Lint"

(i.e. two spaces between "Hello" and "c'Lint"). For simplicity, we assume that string2 will be a subset of string1 .. (i means that string1 will contain string2).

+7
string string-matching c #
source share
6 answers

Do it 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 this helps. It will only remove the first appearance.

+9
source share

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; }); 
+11
source share

you probably want to try

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

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

+6
source share
 string1.Replace(string2, ""); 

Note that this will remove all occurrences of string2 inside string1 .

+5
source share

Above my head, removing the first instance can be done as follows

 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 check before release: o)

+2
source share

Try this one line code only ...

 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
source share

All Articles