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:
- Check if there are leading zeroes.
- If not, simply return the input string.
- If so, remove the first zero and then recur, calling the same method with the first character removed.
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);
}