是否有一个.NET函数来删除字符串开头的第一个(也是第一个)事件?

Jos*_*eph 2 string

我正在使用TrimStart函数执行以下操作:

var example = "Savings:Save 20% on this stuff";
example = example.TrimStart("Savings:".ToCharArray());
Run Code Online (Sandbox Code Playgroud)

我期待这导致示例具有"在这个东西上节省20%"的值.

但是,我得到的是"这个东西的20%".

在阅读了关于TrimStart的文档之后,我明白了为什么,但是现在我想知道.NET中是否有一个函数可以做我最初尝试做的事情?

有没有人知道一个功能,所以我不必创建自己的功能并跟踪它?

Mar*_*ers 10

我不认为这样的方法存在,但是你可以很容易地用做StartsWithSubstring:

s = s.StartsWith(toRemove) ? s.Substring(toRemove.Length) : s;
Run Code Online (Sandbox Code Playgroud)

您甚至可以将其添加为扩展方法:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)