Jump to content
Xtreme .Net Talk

Recommended Posts

Posted
I am trying to output elements of an array to a console window. Is there any built-in formatting command that will allow me to set the width between each of the elements as they are written to the console? I know that in C++ there is the "setw()" command, but is there something similar in C#?
  • *Experts*
Posted

You can use String.Format(), or for each individual string you could try stringvar.PadLeft() or stringvar.PadRight().

 

-Nerseus

"I want to stand as close to the edge as I can without going over. Out on the edge you see all the kinds of things you can't see from the center." - Kurt Vonnegut
Posted
Could someone possibly direct me to some examples of how to use these methods? I can't seem to figure out how to set them up with the proper arguments. Thank you.
  • *Experts*
Posted

// Fill an array for testing
string[] strings = new string[10];
for(int i=0; i<strings.Length; i++) strings[i] = (i * 13).ToString();

for(int i=0; i<strings.Length; i++)
Console.Write("{0,10}", strings[i]);
Console.WriteLine();

 

You can use "{0,-10} in the Console.Write call to left-align.

 

You can use the same format with String.Format as with Console.WriteLine, so:

string s1 = string.empty;
// Fill an array for testing
string[] strings = new string[10];
for(int i=0; i<strings.Length; i++) strings[i] = (i * 13).ToString();

for(int i=0; i<strings.Length; i++)
s1 += String.Format("{0,10}", strings[i]);

Console.WriteLine(s1);

 

 

-Nerseus

"I want to stand as close to the edge as I can without going over. Out on the edge you see all the kinds of things you can't see from the center." - Kurt Vonnegut

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...