user3044294
user3044294

Reputation: 205

how write C# Recursion method?

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

Answers (3)

Ant P
Ant P

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:

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

Upvotes: 6

Sudhakar Tillapudi
Sudhakar Tillapudi

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

Justin Iurman
Justin Iurman

Reputation: 19016

You don't need recursion at all for that.

Instead, use TrimStart to remove all leading 0

StringMobileNo.TrimStart('0')

Upvotes: 2

Related Questions