0

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

            }
2
  • But....... why? Are you really know what recursion means? Commented Feb 23, 2014 at 16:52
  • No i dot know how recursion use Commented Feb 23, 2014 at 16:54

3 Answers 3

6

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:

  1. Check if there are leading zeroes.
  2. If not, simply return the input string.
  3. 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);
}
Sign up to request clarification or add additional context in comments.

Comments

2

You don't need recursion at all for that.

Instead, use TrimStart to remove all leading 0

StringMobileNo.TrimStart('0')

Comments

1

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

     }
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.