How to format output

  • Thread starter Thread starter newbiecpp
  • Start date Start date
N

newbiecpp

How can I format output string. For example, when I use:

Console.WriteLine("12345")

I want to output like

" 12345", i.e., I need set width is 10 and align at right. How can I do
it. I searched MSDN but cannot fine the format string. Thanks.
 
newbiecpp said:
How can I format output string. For example, when I use:

Console.WriteLine("12345")

I want to output like

" 12345", i.e., I need set width is 10 and align at right. How can I do
it. I searched MSDN but cannot fine the format string. Thanks.

Browsing the String.Format method is a good start. The .NET class
library reference will tell you how to use special characters to achieve
proper output.

To solve you problem for now you can use something like this:

int numer = 12345;
string temp = String.Format("{0,10:G", int);
Console.WriteLine(temp);

It will output:

_____12345 // spaces indicated by underscores ("_").


Regards

Catherine
 
Oops! Typo: missed a curly brace:

string temp = String.Format("{0,10:G}", int);

Sorry for that.

Catherine
 
newbiecpp said:
How can I format output string. For example, when I use:

Console.WriteLine("12345")

I want to output like

" 12345", i.e., I need set width is 10 and align at right. How can I
do
it. I searched MSDN but cannot fine the format string. Thanks.
I think I would use something like this:

string myString;
myString= "12345";

if (myString.Length<10)
{
myString = myString.PadLeft(10,' ');
}

Console.WriteLine(myString);
 
format the string before you output it via the console.

just like this:

public static void Main(string[] args)

{

string test="12345";

test=test.PadLeft(10,' ');

Console.WriteLine(test);


}
 
Back
Top