是否有 Remove() 方法也将 return 删除的子字符串?

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

给定 string s = "ABCDEF",我想要类似 Remove() 方法的东西,它也 returns 删除的字符串。例如,类似于:

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

或:

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

或者也许:

s.NewRemove(3, out removed);

您可以轻松编写自己的扩展方法

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);
}

在Python中,这是通过切片完成的:

s = 'ABCDEF'
removed = s[3:]

您可以将其包装在一个函数中:

def remove(string, start, length=None):
    if length is None:
        end = None

    else:
        end = start + length

    return string[start:end]

remove(s, 3, 2)

输出:

DE