Friday, April 20, 2007

formatting your text in c#

some common escape sequence / special character

Escape sequence

Description

\n

Newline. Positions the screen cursor at the beginning of the next line.

\t

Horizontal tab. Moves the screen cursor to the next tab stop.

\r

Carriage return. Positions the screen cursor at the beginning of the current linedoes not advance the cursor to the next line. Any characters output after the carriage return overwrite the characters previously output on that line.

\\

Backslash. Used to place a backslash character in a string.

\"

Double quote. Used to place a double-quote character (") in a string. For example,

Console.Write( "\"in quotes\"" );

displays

"in quotes"



And,
C# has added some nice default features that we can use to format our text/string in console.

string format specifiers.

Format Specifier

Description

C or c

Formats the string as currency. Precedes the number with an appropriate currency symbol ($ in the US). Separates digits with an appropriate separator character (comma in the US) and sets the number of decimal places to two by default.

D or d

Formats the string as a decimal. Displays number as an integer.

N or n

Formats the string with commas and a default of two decimal places.

E or e

Formats the number using scientific notation with a default of six decimal places.

F or f

Formats the string with a fixed number of decimal places (two by default).

G or g

General. Formats the number normally with decimal places or using scientific notation, depending on context. If a format item does not contain a format specifier, format G is assumed implicitly.

X or x

Formats the string as hexadecimal.



example code 1:
Console.Write( "Welcome\nto\nC#\nProgramming!" );

output:
welcome
to
C#
Programming!

example code 2, we will use default string formating ( without string specifier):

Console.WriteLine( "{0}\n{1}", "Welcome to", "C# Programming!" );


output:
Welcome to
C# Programming!

example code 3, this program will show u how to create time format of hh:mm:ss

int hour = 4;
int min = 30;
int sec =23;
Console.WriteLine("time: {0:D2}:{1:D2}:{2:D2}",hour,min,sec);

output:
time: 04:30:23

example code 4, this code will use the string fromat specifier C for currency

Console.WriteLine( "account1 balance: {0:C}", 1000 );

output:
account1 balance: $1,000.00

it's cool, isn't it?

No comments: