Pergunta

I'm using StringBuilder to turn a list into a single string. I don't want the string to have newline breaks, but it automatically adds a new line for each list value appended to the string.

for (int i = 1; i <= ruleN; i++)
{
    string fizz = "F";
    string buzz = "B";
    string fizzBuzz = "FB";
    List<string> numberSet = new List<string>();
    if(i % ruleA == 0 && i % ruleB != 0) //if i is devisible by A  
                                         //but not B
    {
        numberSet.Add(fizz); 
    }
    if(i % ruleB == 0 && i % ruleA != 0) //if i is devisible by B 
                                         //but not A
    {
        numberSet.Add(buzz);
    }
    if(i % ruleA == 0 && i % ruleB ==0) //if i is devisible by both 
                                        //A and B
    {
        numberSet.Add(fizzBuzz);
    }
    if(i % ruleA != 0 && i % ruleB != 0) //if i is devisible by 
                                         //neither A nor B 
    {
        //convert the number to a string and add it to list numberSet
        string undevisible = Convert.ToString(i);
        numberSet.Add(undevisible);

    StringBuilder Builder = new StringBuilder();
    foreach (string number in numberSet)
    {
        // Append each string to the StringBuilder overload.
        Builder.Append(number).Append(" ");
    }
    string output = Builder.ToString();
    Console.WriteLine(output);

The output ends up looking like this:

enter image description here

Where are the newlines coming from?

Foi útil?

Solução

They are coming from your Console.WriteLine(output). Notice that is within your for loop.

Outras dicas

For each 'i', you build a StringBuilder and write Console.WriteLine. That's the newline. Maybe your for cicle had to stop before StringBuilder creation?

Console.WriteLine does exactly that so for each iteration through the first for loop you are writing a new line to the console. If you want it all on one line I would suggest having another stringbuilder object that holds everything you want to write to the console then do a console.writeline after the for loops.

The first loop is closed after printing in console, so every iterations you create a new string builder with new value and then print that using println() method which prints in a new line,

Also try optimizing your code, why you don't use Builder.Append() inside your if statement and don't define variable with the type of list?

If your code is exactly doing this, there's no need to waste memory for that list.

Regards

Hana Bizhani

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top