我使用 TrimStart 函数执行以下操作:
var example = "Savings:Save 20% on this stuff";
example = example.TrimStart("Savings:".ToCharArray());
我预计这会导致示例的值为“在这个东西上节省 20%”。
但是,我得到的是“这个东西的 20%”。
阅读 TrimStart 上的文档后,我明白了原因,但现在我想知道 .NET 中是否有一个函数可以完成我最初想要做的事情?
有人知道一个函数,这样我就不必创建自己的函数并跟踪它吗?
最佳答案
我认为不存在这样的方法,但您可以使用 StartsWith
和 Substring
轻松实现:
s = s.StartsWith(toRemove) ? s.Substring(toRemove.Length) : s;
您甚至可以将其添加为扩展方法:
public static class StringExtension
{
public static string RemoveFromStart(this string s, string toRemove)
{
if (s == null)
{
throw new ArgumentNullException("s");
}
if (toRemove == null)
{
throw new ArgumentNullException("toRemove");
}
if (!s.StartsWith(toRemove))
{
return s;
}
return s.Substring(toRemove.Length);
}
}
关于string - 是否有 .NET 函数可以删除字符串开头的第一个(且仅是第一个)出现的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3105856/