spex5
spex5

Reputation: 1289

Remove last string from the output of my loop

If I have the following program:

class Program
    {
        static void Main()
        {
            for (int i = 1; i < 6; i++)
            {
                Console.Write(i + " potato ");

            }
            Console.ReadLine();
        }
    }
}

This will print out "1 potato 2 potato 3 potato 4 potato 5 potato"

How can I remove the last "potato" so it just says: "1 potato 2 potato 3 potato 4 potato 5 "

Upvotes: 0

Views: 89

Answers (5)

Jeffrey Wieder
Jeffrey Wieder

Reputation: 2376

Add a if check to determine if you are about to print the last record or not.

    static void Main()
    {
        int potatoCount = 5;
        for (int i = 1; i <= potatoCount; i++)
        {
            Console.Write(i);
            //Only print 'Potato' when not on last print
            if (i+1 <= potatoCount) Console.Write(" potato ");
        }
        Console.ReadLine();
    }

Upvotes: 0

bill
bill

Reputation: 771

class Program
 {
    static void Main()
      {
       int max = 5;
        for (int i = 1; i <= max; i++)
        {
          Console.Write(i);
          if(i!=max)   
            Console.Write(" potato ");
        }
        Console.ReadLine();
       }
   }
}

Would do the trick.

Upvotes: 2

Habib
Habib

Reputation: 223247

Why not use String.Join like:

 var result = String.Join(" potato ", Enumerable.Range(1, 5));

If you need trailing space you can do:

var result  = String.Join(" potato ", Enumerable.Range(1, 5)) + " ";

Upvotes: 4

DuckDodger
DuckDodger

Reputation: 83

    class Program
{
    static void Main()
    {
        for (int i = 1; i < 6; i++)
        {
            if( i < 5 )
                Console.Write(i + " potato ");
            else
                Console.Write(i);
        }
        Console.ReadLine();
    }
}

}

Upvotes: 0

a-ctor
a-ctor

Reputation: 3733

You could do this:

for (int i = 1; i < 6; i++)
{
    Console.Write(i + (i != 5 ? " potato " : string.Empty));
}

Upvotes: 5

Related Questions