Alex Rivera | Logout

C# - Simplest way to remove first occurrence of a substring from another string

Asked 2010-02-04T17:04:24.863
135

I need to remove the first (and ONLY the first) occurrence of a string from another string.

Here is an example replacing the string "\\Iteration". This:

ProjectName\\Iteration\\Release1\\Iteration1

would become this:

ProjectName\\Release1\\Iteration1

Here some code that does this:

const string removeString = "\\Iteration";
int index = sourceString.IndexOf(removeString);
int length = removeString.Length;
String startOfString = sourceString.Substring(0, index);
String endOfString = sourceString.Substring(index + length);
String cleanPath = startOfString + endOfString;

That seems like a lot of code.

So my question is this: Is there a cleaner/more readable/more concise way to do this?

Edit
Report

2 Answers

196
int index = sourceString.IndexOf(removeString);
string cleanPath = (index < 0)
    ? sourceString
    : sourceString.Remove(index, removeString.Length);
answered 2010-02-04T17:10:42.993
14

Wrote a quick TDD Test for this

    [TestMethod]
    public void Test()
    {
        var input = @"ProjectName\Iteration\Release1\Iteration1";
        var pattern = @"\\Iteration";

        var rgx = new Regex(pattern);
        var result = rgx.Replace(input, "", 1);
        
        Assert.IsTrue(result.Equals(@"ProjectName\Release1\Iteration1"));
    }

rgx.Replace(input, "", 1); says to look in input for anything matching the pattern, with "", 1 time.

answered 2010-02-04T17:18:52.620

Your Answer