C# – 最简单的方法从另一个string中删除第一次出现的子string

我需要从另一个string中删除第一个(只有第一个)string。

这是一个replacestring"\\Iteration"的例子。 这个:

项目名\\ \\迭代\\ Release1 Iteration1

会变成这样:

项目名\\ \\ Release1 Iteration1

这里有一些代码是这样的:

 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; 

这似乎很多代码。

所以我的问题是:是否有一个更清洁/更可读/更简洁的方式来做到这一点?

 int index = sourceString.IndexOf(removeString); string cleanPath = (index < 0) ? sourceString : sourceString.Remove(index, removeString.Length); 
 string myString = sourceString.Remove(sourceString.IndexOf(removeString),removeString.Length); 

编辑:@OregonGhost是正确的。 我自己会用条件断开脚本来检查这样的事件,但是我是在假设这些string按照某种要求被给予彼此属性的情况下运行的。 预计业务所需的exception处理规则可能会抓住这种可能性。 我自己会使用一些额外的行来执行有条件的检查,并且对于那些可能没有花时间仔细阅读的初级开发人员来说,这样做更容易一些。

为此写了一个快速的TDDtesting

  [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); 说,看看input的任何匹配的模式,用“”,1次。

 sourceString.Replace(removeString, ""); 

你可以使用扩展方法来获得乐趣。 通常,我不build议将扩展方法附加到像string这样的通用类,但正如我所说这很有趣。 我借用了卢克的回答,因为重新发明车轮毫无意义。

 [Test] public void Should_remove_first_occurrance_of_string() { var source = "ProjectName\\Iteration\\Release1\\Iteration1"; Assert.That( source.RemoveFirst("\\Iteration"), Is.EqualTo("ProjectName\\Release1\\Iteration1")); } public static class StringExtensions { public static string RemoveFirst(this string source, string remove) { int index = source.IndexOf(remove); return (index < 0) ? source : source.Remove(index, remove.Length); } } 

我绝对同意这是一个扩展方法的完美,但我认为它可以提高一点。

 public static string Remove(this string source, string remove, int firstN) { if(firstN <= 0 || string.IsNullOrEmpty(source) || string.IsNullOrEmpty(remove)) { return source; } int index = source.IndexOf(remove); return index < 0 ? source : source.Remove(index, remove.Length).Remove(remove, --firstN); } 

这会做一些有趣的recursion。

这里还有一个简单的unit testing:

  [TestMethod()] public void RemoveTwiceTest() { string source = "look up look up look it up"; string remove = "look"; int firstN = 2; string expected = " up up look it up"; string actual; actual = source.Remove(remove, firstN); Assert.AreEqual(expected, actual); }