给出string s = "ABCDEF"
,我想要类似Remove()
方法的方法,该方法也返回删除的字符串。例如,类似:
string removed = s.NewRemove(3); // removed is "DEF"
或:
string removed = s.NewRemove(3,2); // removed is "DE"
或者也许:
s.NewRemove(3, out removed);
答案 0 :(得分:2)
您可以轻松编写自己的扩展方法
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);
}
答案 1 :(得分:1)
在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