我想写下面的循环使用C# Recursion请指导我.谢谢 !
StringMobileNo = value.ToString();
for (int i = 0; i < 3; i++)
{
if (StringMobileNo.StartsWith("0"))
{
StringMobileNo = StringMobileNo.Remove(0, 1);
}
}
Run Code Online (Sandbox Code Playgroud)
如果要递归删除前导零,可以执行以下操作:
public string RemoveZeroes(string input)
{
if (!input.StartsWith("0"))
return input;
return RemoveZeroes(input.Remove(0, 1));
}
Run Code Online (Sandbox Code Playgroud)
一个解释:
这将导致方法重复,直到最后没有前导零,此时结果字符串 - 删除所有前导零 - 将一直返回到调用堆栈.
然后这样打电话:
var myString = RemoveZeroes(StringMobileNo);
Run Code Online (Sandbox Code Playgroud)
但是,只需执行以下操作即可实现:
StringMobileNo.TrimStart('0');
Run Code Online (Sandbox Code Playgroud)
请注意,我在这里假设i < 3条件是一个任意退出条件,你实际上想要删除所有前导零.这是一个可以指定删除的数量:
public string RemoveZeroes(string input, int count)
{
if (count < 1 || !input.StartsWith("0"))
return input;
return RemoveZeroes(input.Remove(0, 1), count - 1);
}
Run Code Online (Sandbox Code Playgroud)