Search code examples
c#stringconsole.writeline

Creating a string variable with specific spacing (using \t) similar to Console.WriteLine


How I could make this (broken) piece of code work:

aString = ("{0}\t{1}  \t{2}\t{3}", array[0], array[1], array[2], array[3]);

The string would take different elements from an array and put them into a new string which was formatted with the spacing shown above if it were to be produced through Console.WriteLine (which in this instance, since the array is calculated external to the main method, is not suitable.)

This string would then be returned and passed back to the main method. Is there a way to create a string with specific spacing such as the above in an easy manner?


Solution

  • Use the String.Format method, like so:

    aString = String.Format("{0}\t{1}  \t{2}\t{3}", array[0], array[1], array[2], array[3]);