Composite formatting appendformat characters

Source: Internet
Author: User
ArticleDirectory
    • Composite string
    • Syntax
    • Sample Code

The. NET Framework composite Formatting Function uses the Object List and composite format string as the input. A composite string consists of fixed text and index placeholders. An index placeholder is a format item that corresponds to objects in the list. The result string generated by the formatting operation is composed of the original fixed text and the string representation of the object in the list.

Methods such as format and appendformat and some heavy loads of writeline and textwriter. writeline support the compound Formatting Function. The string. Format method generates the formatted result string,AppendformatMethod: append the formatted result string to the stringbuilder object. The console. writeline method displays the formatted result string to the console. The textwriter. writeline method writes the formatted result string to a stream or file.

Composite string

The composite format string and Object List are used as parameters to support the composite Formatting Function. A composite string consists of zero or multiple fixed text segments and one or more format items. Fixed text is any selected string, and each format item corresponds to an object or boxed structure in the list. The compound Formatting Function returns a new result string. Each format item is replaced by the string representation of the corresponding object in the list.

Consider the following:Format Code.

C #

Copy code

String myname = "Fred"; string. Format ("name = {0}, hours = {1: hh}", myname, datetime. Now );

The fixed text is"Name =And, Hours =". The format item is"{0}And{1: hh}", The former index is 0, corresponding to the objectMynameThe index of the latter is 1, corresponding to the objectDatetime. Now.

Syntax

Each format item adopts the following format and contains the following components:

{ Index[,Alignment] [:Format String]}

Braces ("{" and "}") must be used in pairs.

Index component

The mandatory "Index" component (also known as the parameter specifier) is a number starting from 0 and can identify the corresponding items in the object list.That is to say, the first object in the list is formatted for the format item with the parameter description 0, the second object in the list is formatted for the format item with the parameter description 1, and so on.

By specifying the same parameter specifiers, multiple format items can reference the same element in the object list. For example, by specifying a composite string similar to "{0: x} {0: e} {0: n, you can format the same value in hexadecimal, scientific notation, and numeric format.

Each format item can reference any object in the list. For example, if there are three objects, You Can format the second, first, and third objects by specifying a composite string similar to "{1} {0} {2. Objects not referenced by format items are ignored. If the parameter description specifies an item that is out of the range of the Object List, an exception occurs during running.

Alignment component

The optional alignment component is a signed integer that indicates the width of the preferred formatted field. If the value of alignment is smaller than the length of the formatted string, alignment is ignored and the length of the formatted string is used as the field width. If "alignment" is positive, the formatted data in the field is right aligned. If "alignment" is negative, the formatted data in the field is left aligned.If you need to fill in, use blank space. If "alignment" is specified, use a comma.

Format String component

The optional "Format String" component is a format string suitable for the object type being formatted.If the corresponding object is a numeric value, the numeric format string is specified. If the corresponding object is a datetime object, the date and time format strings are specified, or if the corresponding object is an enumeration value, specifies the enumerated format string. If "Format String" is not specified, regular ("G") format specifiers are used for numbers, dates, and times, or enumeration types.If you specify a "format specifier", you must use a colon.

Escape braces

The left and right braces are interpreted as the start and end of the format item. Therefore, you must use the escape sequence to display the Left or Right braces of the text. Specify two left braces ("{") in the fixed text to display a left braces ("{"), or two right braces ("}}") to display a right braces ("}"). Explain the braces in sequence. Nested braces cannot be interpreted.

Interpreting the escape braces will lead to unexpected results. For example, you need to display a left braces, a numeric value formatted as a decimal number, and a format item "{0: D }}}" in the right braces }}}". However, the format item is interpreted as follows:

    1. The first two left braces ("{") are escaped to generate a left braces.

    2. The subsequent three characters ("{0:") are interpreted as the beginning of the format item.

    3. The next character ("D") will be interpreted as a decimal standard value format specifier, but the two escape braces ("}") below generate a single braces. Because the obtained string ("d}") is not a standard value format specifier, the resulting string is interpreted as a custom format string used to display the string "d.

    4. The last braces ("}") are interpreted as the end of the format item.

    5. The final result is the string "{d }". The value to be formatted is not displayed.

When writing code, one way to avoid false interpretations of escape braces and format items is to format the braces and format items separately. That is to say, the left braces of the text are displayed in the first formatting operation, the results of the format items are displayed in the next operation, and the right braces of the text are displayed in the last operation.

Processing sequence

If the value to be formatted isNull(In Visual BasicNothingReturns an empty string ("").

If the icustomformatter interface is implemented for the type to be formatted, The icustomformatter. Format method is called.

If the preceding step is not formatted and the type implements the iformattable interface, the iformattable. tostring method is called.

If the preceding step is not formattedTostringMethod (inherited from the object class ).

After the preceding steps are completed, the application is aligned.

Sample Code

The following example shows a string created using composite formatting andTostringMethod to create another string. The two formatting types produce the same results.

C #

Copy code

 
String formatstring1 = string. Format ("{0: dddd mmmm}", datetime. Now); string formatstring2 = datetime. Now. tostring ("dddd mmmm ");

Assume that the current date is Thursday, January 1, May. The values of the two strings in the preceding example areThursday May.

Console. writelineAndString. FormatMake public the same features. The only difference between the two methods isString. FormatReturns the result as a string, whileConsole. writelineWrite the resultConsoleThe output stream associated with the object. The following example usesConsole. writelineMethodMyintIs formatted as a currency value.

C #

Copy code

 
Int Myint = 100; console. writeline ("{0: c}", Myint );

This code is run on a computer in the U.S. English region.$100.00Displayed on the console.

The following example shows how to format multiple objects, including formatting an object in two different ways.

C #

Copy code

String myname = "Fred"; string. format ("name = {0}, hours = {1: hh}, minutes = {1: mm}", myname, datetime. now );

The output of the above string is"Name = Fred, hours = 07, minutes = 23", The current time reflects these numbers.

The following example shows how to use alignment in formatting. The formatted parameters are placed between the vertical bars (|) to highlight the alignment.

C #

Copy code

String myfname = "Fred"; string mylname = "opals"; int Myint = 100; string formatfname = string. format ("First name = | {0, 10} |", myfname); string formatlname = string. format ("last name = | {0, 10} |", mylname); string formatprice = string. format ("Price = | {0, 10: c} |", Myint); console. writeline (formatfname); console. writeline (formatlname); console. writeline (formatprice); formatfname = string. format ("First name = | {0,-10} |", myfname); formatlname = string. format ("last name = | {0,-10} |", mylname); formatprice = string. format ("Price = | {0,-10: c} |", Myint); console. writeline (formatfname); console. writeline (formatlname); console. writeline (formatprice );

In the U.S. English language, the above Code displays the following content on the console. Different currency symbols and separators are displayed in different regions.

Copy code

 
First name = | Fred | last name = | opals | price = | $100.00 | First name = | Fred | last name = | opals | price = | $100.00 |

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.