我需要从另一个字符串中删除第一个(并且只是第一个)字符串.
这是替换字符串的示例"\\Iteration"
.这个:
ProjectName\\Iteration\\Release1\\Iteration1
会成为这样的:
ProjectName\\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;
Run Code Online (Sandbox Code Playgroud)
这似乎是很多代码.
所以我的问题是:是否有更清晰/更可读/更简洁的方法来做到这一点?
Luk*_*keH 131
int index = sourceString.IndexOf(removeString);
string cleanPath = (index < 0)
? sourceString
: sourceString.Remove(index, removeString.Length);
Run Code Online (Sandbox Code Playgroud)
Joe*_*ton 24
string myString = sourceString.Remove(sourceString.IndexOf(removeString),removeString.Length);
Run Code Online (Sandbox Code Playgroud)
编辑:@OregonGhost是对的.我自己会用条件来破坏脚本来检查这种情况,但是我假设字符串被某些要求赋予彼此属性.预计业务所需的异常处理规则可能会捕获这种可能性.我自己会使用一些额外的行来执行条件检查,并且对于那些可能没有花时间仔细阅读它的初级开发人员来说,它会更具可读性.
mal*_*ron 23
sourceString.Replace(removeString, "");
Run Code Online (Sandbox Code Playgroud)
Caf*_*eek 10
为此写了一个快速的TDD测试
[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"));
}
Run Code Online (Sandbox Code Playgroud)
rgx.Replace(input,"",1); 说要查看任何与模式匹配的输入,用"",1次.
如果您想要一个简单的方法来解决这个问题。(可作为扩展使用)
见下文:
public static string RemoveFirstInstanceOfString(this string value, string removeString)
{
int index = value.IndexOf(removeString, StringComparison.Ordinal);
return index < 0 ? value : value.Remove(index, removeString.Length);
}
Run Code Online (Sandbox Code Playgroud)
用法:
string valueWithPipes = "| 1 | 2 | 3";
string valueWithoutFirstpipe = valueWithPipes.RemoveFirstInstanceOfString("|");
//Output, valueWithoutFirstpipe = " 1 | 2 | 3";
Run Code Online (Sandbox Code Playgroud)
受到@LukeH 和@Mike 答案的启发并修改。
不要忘记 StringComparison.Ordinal 以防止区域性设置出现问题。 https://www.jetbrains.com/help/resharper/2018.2/StringIndexOfIsCultureSpecific.1.html
您可以使用扩展方法来获得乐趣.通常我不建议将扩展方法附加到像字符串这样的通用类,但就像我说这很有趣.我借用了@Luke的回答,因为没有必要重新发明轮子.
[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);
}
}
Run Code Online (Sandbox Code Playgroud)