Dāvis Augulis
Dāvis Augulis

Reputation: 11

How to make my code output comma after all values that go under criteria besides the last

Code needs to output comma after values that go under criteria, besides the last one, can't seem to find a way how to make code ignore the last comma.

public class LabWork1
{
    public static void Main(string[] args)
    {
        Console.Write("n: ");
        int n = int.Parse(Console.ReadLine());
        var numbers = new StringBuilder();

        for (int i = 1; i <= n; i++)
        { 
            if (i % 3 == 0 || i % 5 == 0)
            {
                numbers.Append(i);
                numbers.Append(", ");
            }
        }

        Console.Write(numbers.ToString());
    }
}

Should be

3, 5, 6, 9

Actual (note the last comma)

3, 5, 6, 9,

Upvotes: 0

Views: 79

Answers (3)

Prasad Telkikar
Prasad Telkikar

Reputation: 16079

You can use others solutions to ignore extra comma from string builder.

But if you want to remove , from existing code, you can trim comma and space.

You can use TrimEnd(',', ' ') to trim last comma and space from output string

Console.Write(numbers.ToString().TrimEnd(',', ' '));

MSDN: .TrimEnd()


Second approach:

Instead of appending i in string builder, store it in List<int>. While writing numbers to console use string.Join().

MSDN : string.Join(string separator, IEnumerable<T> values)

Concatenates the members of a constructed IEnumerable collection of type String, using the specified separator between each member

Your solution will look like

...
//Store all i's in list
List<int> numbers = new List<int>(); 
for (int i = 1; i <= n; i++)
{ 
    if (i % 3 == 0 || i % 5 == 0)
        numbers.Add(i);
}

Console.Write(string.Join(", ", numbers));
...

Upvotes: 0

Salah Akbari
Salah Akbari

Reputation: 39966

You can simply use string.Join and LINQ instead:

var numbers = string.Join(", ", Enumerable.Range(1 , n)
                                .Where(i => i % 3 == 0 || i % 5 == 0));
Console.Write(numbers);

Just make sure that you have already added the following to your using directive:

using System.Linq;

Upvotes: 4

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186803

To repair your current solution, add comma , before adding i: when having empty numbers add i; if numbers is not empty, add ", " first and then i.

    ...
    for (int i = 1; i <= n; i++)
    { 
            if (i % 3 == 0 || i % 5 == 0)
            {
                    // Add comma (if required) first...
                    if (numbers.Length > 0)
                            numbers.Append(", ");        

                    // ...and only then value
                    numbers.Append(i);
            }
    }
    ...

Upvotes: 1

Related Questions