Reputation: 205
i want to write following for loop by using C# Recursion
please guide me . Thank you !
StringMobileNo = value.ToString();
for (int i = 0; i < 3; i++)
{
if (StringMobileNo.StartsWith("0"))
{
StringMobileNo = StringMobileNo.Remove(0, 1);
}
}
Upvotes: 0
Views: 160
Reputation: 25221
If you want to recursively remove leading zeroes, you can do this:
public string RemoveZeroes(string input)
{
if (!input.StartsWith("0"))
return input;
return RemoveZeroes(input.Remove(0, 1));
}
An explanation:
This will cause the method to recur until, finally, there are no leading zeroes, at which point the resulting string - with all leading zeroes removed - will be returned all the way up the call stack.
Then call like so:
var myString = RemoveZeroes(StringMobileNo);
However, the same can be achieved by simply doing:
StringMobileNo.TrimStart('0');
Note that I have assumed here that the i < 3
condition is an arbitrary exit condition and you actually want to remove all leading zeroes. Here's one that will let you specify how many to remove:
public string RemoveZeroes(string input, int count)
{
if (count < 1 || !input.StartsWith("0"))
return input;
return RemoveZeroes(input.Remove(0, 1), count - 1);
}
Upvotes: 6
Reputation: 26199
I think you don't need to use Recursion
function here.
you can Use String.TrimStart("0")
but if you want to use Recursion
function
Try This:
class Program
{
static void Main(string[] args)
{
Recursion("000012345",0);
}
static void Recursion(string value,int c)
{
String MobileNo = value;
int count=c;
if (MobileNo.StartsWith("0") && count<3)
{
count++;
Recursion(MobileNo.Remove(0, 1),count);
}
}
}
Upvotes: 1
Reputation: 19016
You don't need recursion at all for that.
Instead, use TrimStart
to remove all leading 0
StringMobileNo.TrimStart('0')
Upvotes: 2