Use C # To Format a string

Source: Internet
Author: User
Tags iso 8601
Use C # To Format a string
1 Preface

If you are familiar with Microsoft Foundation Classes (MFC) cstring, Windows Template Library (wtl) cstring or standard template library (STL) string class. you must be familiar with the format method. This method is often used in C # To format strings, such as the following:

Int x = 16;
Decimal y = 3.57 m;
String H = string. Format ("item {0} sells at {1: c}", x, y );
Console. writeline (h );
On my machine, we can get the following output:

Item 16 sells at ¥3.57
Maybe the output on your machine is not the same as this one. This is normal and will be explained later in this article.

In our daily use, we use the console. writeline method to output a string. In fact, String. Format and console. writeline have many things in common. Both methods have many reload formats and use an array of objects without fixed parameters as the last parameter. The following two statements generate the same output.

Console. writeline ("Hello {0} {1} {2} {3} {4} {5} {6} {7} {8}", 123, 45.67, true, 'Q', 4, 5, 6, 7, '8 ');
String u = string. format ("Hello {0} {1} {2} {3} {4} {5} {6} {7} {8}", 123, 45.67, true, 'Q', 4, 5, 6, 7, '8 ');
Console. writeline (U );
The output is as follows:

Hello 123 45.67 true Q 4 5 6 7 8
Hello 123 45.67 true Q 4 5 6 7 8
2 string format

Both string. Format and writeline follow the same format rules. The format is as follows: "{n [, m] [: formatstring]}", arg1,... argn, in this format:

1) N is an integer starting from 0, indicating the number of parameters to be formatted

2) M is an optional integer that represents the width of the formatted parameter. If M is a negative number, the formatted value is left aligned. If M is a positive number, the formatted value is right aligned.

3) formatstring is another optional parameter, indicating the formatCode

Argn indicates the expression to be formatted, which corresponds to n.

If argn is null, it is replaced by an empty string. If no formatstring exists, use the tostring method corresponding to parameter n to format it. The following statement generates the same output:

Public class testconsoleapp
{
Public static void main (string [] ARGs)
{
Console. writeline (123 );
Console. writeline ("{0}", 123 );
Console. writeline ("{0: D3}", 123 );
}
}
The output is:

123
123
123
You can also use string. format to get the same output.

String S = string. Format ("123 ");
String T = string. Format ("{0}", 123 );
String u = string. Format ("{0: D3}", 123 );
Console. writeline (s );
Console. writeline (t );
Console. writeline (U );
The conclusion is as follows:

(, M) determines the width and alignment direction of the formatted string.

(: Formatstring) determines how to format data, such as using currency symbols, scientific notation, or hexadecimal notation. As shown below:

Console. writeline ("{123,456} {}",); // right aligned
Console. writeline ("{0,-5} {1,-5}", 123,456); // left alignment
The output is

123 456
123 456
You can also combine these expressions with a comma and a colon. Like this:

Console. writeline ("{0,-10: D6} {1,-10: D6}", 123,456 );
The output is:

000123 000456
We can use this formatting feature to align our output.

Console. writeline ("/n {0,-10} {1,-3}", "name", "salary ");
Console. writeline ("----------------");
Console. writeline ("{0,-10} {123456}", "Bill );
Console. writeline ("{0,-10} {7890}", "Polly );
The output is:

Name salary
----------------
Bill 123456
Polly 7890
3. format the identifier.

The standard mathematical Format String is used to return the commonly used string. They are usually in the format of x0. X is a format identifier, and 0 is a precision identifier. There are nine types of format identifiers, which represent most commonly used numeric formats. As shown in the following table:

Letter meaning
C or C currency format
D or D decimal in decimal format (do not confuse the decimal data type with. Net)
E or e exponent index format
Fixed precision format of f or F Fixed Point
Common g or G General formats
N or N are separated by commas (,). For example, 1234 is changed to 1,234.
P or P percentage percentile format
R or r round-trip round (only for floating point numbers) Ensure that a number can be converted back to the same number after being converted into a string
X or X hex hexadecimal format

If we use the following expression, let's see what will happen.

public class formatspecapp
{< br> Public static void main (string [] ARGs)
{< br> int I = 123456;
console. writeline ("{0: c}", I); // ¥123,456.00
console. writeline ("{0: d}", I); // 123456
console. writeline ("{0: e}", I); // 1.234560e + 005
console. writeline ("{0: f}", I); // 123456.00
console. writeline ("{0: g}", I); // 123456
console. writeline ("{0: n}", I); // 123,456.00
con Sole. writeline ("{0: p}", I); // 12,345,600.00%
console. writeline ("{0: x}", I ); // 1e240
}< BR >}< br> the precise control mark controls the number of valid digits or the number of decimal digits.

Console. writeline ("{0: C5}", I); // ¥123,456.00
Console. writeline ("{0: D5}", I); // 123456
Console. writeline ("{0: E5}", I); // 1.23456e + 005
Console. writeline ("{0: F5}", I); // 123456.00000
Console. writeline ("{0: G5}", I); // 1.23456e5
Console. writeline ("{0: N5}", I); // 123,456.00000
Console. writeline ("{0: P5}", I); // 12,345,600.00000%
Console. writeline ("{0: X5}", I); // 1e240
The R (circle) format is only valid for floating point numbers. The value is first formatted in a common format. The dual-precision number has 15-bit precision, and the single-precision number has 7-bit precision. If this value can be correctly parsed back to the original number, it will be formatted with a common format character. If it cannot be parsed back, it will use 17-bit precision to format the double-precision number and 9-bit precision to format the single-precision number. Although we can add the number of digits of a valid number to the end of the circle identifier, it will be ignored.

Double D = 1.2345678901234567890;
Console. writeline ("floating-point:/t {0: F16}", d); // 1.2345678901234600
Console. writeline ("roundtrip:/t {0: R16}", d); // 1.2345678901234567
If the standard format identifier does not meet your requirements. You can use a string in graphical format to create custom string output. Graphical formatting uses placeholders to represent the minimum digits,

The maximum number of digits, the positioning symbol, the appearance of the negative sign, and the appearance of other digital symbols. As shown in the following table.

Symbol name meaning
0 0 placeholder fill in the number of digits below 0
# Use a digit placeholder # to replace the actual number of digits
. Decimal point
, The Delimiter is separated by commas (,). For example, 1000 is divided into 1,000.
% Percentile indicates a percentile.
E + 0
E-0
E + 0
E-0 exponent symbols formatted output with exponent symbols
/A specific character is used for the formatting sequence of the traditional format, such as "/N" (new line)
'Abc'
"ABC" constant string displays strings in single quotes or double quotation marks
; Area separator if the number is formatted as an integer, negative number, or 0, separated;
,. Zoom symbol number divided by 1000

See the following example:

Double I = 123456.42;
Console. writeline ();
Console. writeline ("{0: 00. 00}", I); // 123456.42
Console. writeline ("{0: 00. 00000000e + 0}", I); // 12.34564200e + 4
Console. writeline ("{0: 0,.}", I); // 123
Console. writeline ("{0: #0.000}", I); // 123456.420
Console. writeline ("{0: #0.000; (#0.000)}", I); // 123456.420
Console. writeline ("{0: #0.000; (#0.000); <zero >}", I); // 123456.420
Console. writeline ("{0 :#%}", I); // 12345642%

I =-123456.42;
Console. writeline ();
Console. writeline ("{0: 00. 00}", I); //-123456.42
Console. writeline ("{0: 00. 00000000e + 0}", I); //-12.34564200e + 4
Console. writeline ("{0: 0,.}", I); //-123
Console. writeline ("{0: #0.000}", I); //-123456.420
Console. writeline ("{0: #0.000; (#0.000)}", I); // (123456.420)
Console. writeline ("{0: #0; (#0); <zero >}", I); // (123456)
Console. writeline ("{0 :#%}", I); //-12345642%

I = 0;
Console. writeline ();
Console. writeline ("{0: 0,.}", I); // 0
Console. writeline ("{0: #0}", I); // 0
Console. writeline ("{0: #0; (#0)}", I); // 0
Console. writeline ("{0: #0; (#0); <zero >}", I); // <zero>
Console. writeline ("{0 :#%}", I); // %
4. numeric string parsing

All basic types have the tostring method, which is inherited from the object type. All numeric types have the parse method, which uses strings as parameters and returns equal values. For example

Public class numparsingapp
{
Public static void main (string [] ARGs)
{
Int I = int. parse ("12345 ");
Console. writeline ("I = {0}", I );

Int J = int32.parse ("12345 ");
Console. writeline ("J = {0}", J );

Double D = double. parse ("1.2345e + 6 ");
Console. writeline ("d = {0: f}", d );

String S = I. tostring ();
Console. writeline ("s = {0}", S );
}
}
Output:

I = 12345.
J = 12345
D = 1234500.00
S = 12345
By default, some non-numeric characters can exist. For example, the white space at the beginning and end. Comma and decimal point, plus sign and minus sign. Therefore, the following parse statement is the same

String T = "-1,234,567.890 ";
// Double G = double. parse (t); // same as the following code
Double G = double. parse (t,
Numberstyles. allowleadingsign |
Numberstyles. allowdecimalpoint |
Numberstyles. allowthousands |
Numberstyles. allowleadingwhite |
Numberstyles. allowtrailingwhite );
Console. writeline ("G = {0: f}", G );
The output is like this.

G =-1234567.89
Note that if you want to use numberstyles, you need to add a reference to system. Globalization, and then you can use a combination of different numberstyles or any of them. To be compatible with currency symbols, you need to use the overloaded parse method, which uses the numberformatinfo object as a parameter. Then you can set the currencysymbol attribute of numberformatinfo to call the parse method. For example:

String u = "¥-1,234,567.890 ";
Numberformatinfo ni = new numberformatinfo ();
Ni. currencysymbol = "¥ ";
Double H = double. parse (u, numberstyles. Any, Ni );
Console. writeline ("H = {0: f}", H );
The above Code has the following output:

H =-1234567.89
In addition to numberformatinfo, you can also use the cultureinfo class. Cultureinfo represents a specific culture, including cultural names, writing methods, and calendar formats. Operations in a specific culture are very common, such as formatting dates and sorting. The naming method of culture follows the rfc1766 standard and uses the <language code 2>-<country/region code 2> method, where <language code 2> is two lower-case letters, they are from ISO639-1; <country/region code 2> are two uppercase letters, they are from iso00006. For example, American English is "En-us ". English is "En-GB ". The English language of Trinidad and Tobago is "En-TT ". For example, we can create a cultureinfo object in American English and convert numbers into strings based on this culture.

Int K = 12345;
Cultureinfo US = new cultureinfo ("En-us ");
String v = K. tostring ("C", US );
Console. writeline (v );
The output is:

$12,345.00
Note that we use the reload tostring method, which treats the first formatted string as the first parameter and uses a cultureinfo object (which executes the iformatprovider object) as the second parameter. Here is the second example for Danes:

Cultureinfo Dk = new cultureinfo ("Da-DK ");
String W = K. tostring ("C", DK );
Console. writeline (w );
The output is:

KR 12.345, 00
5 string and date

A date object has a property called ticks. It stores the time interval of January 1 nanoseconds since twelve o'clock A.M., January 1, 100. For example, if the ticks value is 31241376000000000l, it indicates the time for Friday, January 1, and twelve o'clock A.M. Ticks always Increments at an interval of 100 nanoseconds.

The datetime value is represented by the standard or custom method stored in the datetimeformatinfo instance. To modify the date display mode, the datetimeformatinfo instance must be writable so that we can write the custom format and store it in the attribute.

Using system. Globalization;

Public class datesapp
{
Public static void main (string [] ARGs)
{
Datetime dt = datetime. now;
Console. writeline (DT );
Console. writeline ("date = {0}, time = {1}/N ",
DT. Date, DT. timeofday );
}
}
The code will generate the following output:

23/06/2001 17:55:10
date = 23/06/2001 00:00:00, time = 17:55:10. 3839296
The following table lists standard format strings and related datetimeformatinfo attributes.

d
D mm/DD/YYYY 1_datepattern (short date mode)
D dddd, Mmmm DD, yyyy longdatepattern (long date mode)
F dddd, Mmmm DD, yyyy hh: mm full date and time (long date and short time) (full date and time mode)
F dddd, Mmmm DD, yyyy hh: mm: SS fulldatetimepattern (long date and long time)
g mm/DD/YYYY hh: MM General (short date and short time) (general mode, short date and short time)
g mm/DD/YYYY hh: mm: SS General (short date and long time) (general mode, short date and long time)
M, M mmmm dd monthdaypattern (Monthly day mode)
R, r ddd, dd Mmm yyyy, HH ': 'mm': 'ss' gmt' rfc1123pattern (rfc1123 mode)
S yyyy-mm-dd hh: mm: SS sortabledatetimepattern (conforms to ISO 8601) using local time (using local time sorting mode)
T hh: Mm shorttimepattern (short time mode)
T hh: MM: SS longtimepattern (long time mode)
U yyyy-mm-dd hh: mm: SS universalsortable-datetimepattern (conforms to ISO 8601) using Universal Time (General sorting mode)
U dddd, Mmmm DD, yyyy, HH: mm: SS universalsortable-datetimepattern (General sorting mode)
y, Y Mmmm, yyyy yearmonthpattern (yyyy)

The datetimeformatinfo. invariantinfo attribute obtains the default read-only datetimeformatinfo instance, which has nothing to do with culture. You can create a custom mode. Note that invariantinfo is not necessarily the same as the local format. Invariant is in the US format. In addition, if the second parameter you pass to the datetime. Format method is null, datetimeformatinfo will be the default currentinfo. For example

Console. writeline (Dt. tostring ("D", dtfi ));
Console. writeline (Dt. tostring ("D", null ));
Console. writeline ();
The output is

06/23/2001
23/06/2001
Compare and select invariantinfo and currentinfo.

datetimeformatinfo dtfi;
console. Write ("[I] nvariant or [c] urrent info?: ");
If (console. read () = 'I')
dtfi = datetimeformatinfo. invariantinfo;
else
dtfi = datetimeformatinfo. currentinfo;
datetimeformatinfo dtfi = datetimeformatinfo. invariantinfo;
console. writeline (DT. tostring ("D", dtfi);
console. writeline (DT. tostring ("F", dtfi);
console. writeline (DT. tostring ("F", dtfi);
console. writeline (DT. tostring ("g", dtfi);
console. writeline (DT. tostring ("g", dtfi);
console. writeline (DT. tostring ("M", dtfi);
console. writeline (DT. tostring ("r", dtfi);
console. writeline (DT. tostring ("S", dtfi);
console. writeline (DT. tostring ("T", dtfi);
console. writeline (DT. tostring ("T", dtfi);
console. writeline (DT. tostring ("u", dtfi);
console. writeline (DT. tostring ("u", dtfi);
console. writeline (DT. tostring ("D", dtfi);
console. writeline (DT. tostring ("Y", dtfi);
console. writeline (DT. tostring ("DD-mmm-yy", dtfi);
the output is

[I] nvariant or [c] urrent info? : I
01/03/2002
03/01/2002

Thursday, 03 January 2002
Thursday, 03 January 2002
Thursday, 03 January 2002 12:55:03

01/03/2002 12:55:03
January 03
Thu, 03 Jan 2002 12:55:03 GMT
2002-01-03t12: 55: 03
12: 55
12:55:03
2002-01-03 12: 55: 03z
Thursday, 03 January 2002 12:55:03
01/03/2002
2002 January
03-Jan-02

[I] nvariant or [c] urrent info? : C
03/01/2002
03/01/2002

03 January 2002
03 January 2002
03 January 2002 12:55:47
03/01/2002
03/01/2002 12:55:47
03 January
Thu, 03 Jan 2002 12:55:47 GMT
2002-01-03t12: 55: 47
12: 55
12:55:47
2002-01-03 12: 55: 47z
03 January 2002 12:55:47
03/01/2002
January 2002
03-Jan-02 from http://blog.csdn.net/aMao_14189/article/details/2444328

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.