Search code examples
c#stringstringbuilder

Is there a Remove() method that will also return the removed substring?


Given string s = "ABCDEF", I would like something like the Remove() method, which also returns the removed string. For example, something like:

string removed = s.NewRemove(3); // removed is "DEF"

or:

string removed = s.NewRemove(3,2); // removed is "DE"

or maybe:

s.NewRemove(3, out removed);

Solution

  • You could easily write your own extension method

    public static string Remove(this string source, int startIndex, int count,out string removed)
    {
       if (startIndex < 0) throw new ArgumentOutOfRangeException(nameof(startIndex));
       if (count < 0) throw new ArgumentOutOfRangeException(nameof(count));
       if (count > source.Length - startIndex) throw new ArgumentOutOfRangeException(nameof(count));
    
       removed = source.Substring(startIndex, count);   
       return source.Remove(startIndex, count);
    }