Usage of string format in Java

Source: Internet
Author: User
Tags iso 8601 iso 8601 format

The string class has a very useful static method string. Format ():

Format (locale L, string format, object... ARGs) returns a formatted string using the specified language environment, format string, and parameters.

Format (string format, object... ARGs) returns a formatted string using the specified format string and parameters.

1. format the integer: % [index $] [ID] [minimum width] conversion method.

We can see that the formatted string consists of four parts. The meaning of % [index $] is described above, and the meaning of [minimum width] is also well understood, the minimum number of digits in the string to be converted. Let's take a look at the meanings of the remaining two parts:

MARK:

'-' Is left aligned within the minimum width. It cannot be used together with "fill with 0 ".

'#' Is only applicable to octal and hexadecimal. In octal, a hexadecimal value is added before the result and 0x is added before the result.

The '+' result always contains a symbol (generally, it is only applicable to hexadecimal notation. if the object is biginteger, it can be used in hexadecimal notation and hexadecimal notation)

''Plus space before a positive value and negative value plus a negative number (generally only applicable to the 10-digit system. If the object is biginteger, it can be used in the 8-and 16-digit systems)

The '0' result is filled with zero.

',' Is only applicable to the 10-digit system. Each three digits are separated by commas (,).

'(If the parameter is a negative number, enclose The number in parentheses instead of adding a negative number in the result (the same as' +)

Conversion Method:

D-decimal o-octal X or X-hexadecimal

The above description is too boring. Let's look at some specific examples. Note that most of the logo characters can be used at the same time.

System. out. println (string. format ("% 1 $, 09d",-3123); system. out. println (string. format ("% 1 $ 9d",-31); system. out. println (string. format ("% 1 $-9d",-31); system. out. println (string. format ("% 1 $ (9d",-31); system. out. println (string. format ("% 1 $ # 9x", 5689); // The result is:
//-0003,123 //-31 //-31 // (31) // 0x1639

2. format the floating point: % [index $] [ID] [minimum width] [. Precision] Conversion Method

We can see that the floating point conversion has an "precision" option, which can control the number of digits after the decimal point.

Identifier:

'-' Is left aligned within the minimum width. It cannot be used together with "fill with 0 ".

The '+' result always contains a symbol.

''Plus spaces before positive values and minus signs before negative values

The '0' result is filled with zero.

',' Each three digits are separated by commas (,) (only applicable to fgg conversions)

'(If the parameter is a negative number, enclose The number in parentheses instead of adding a negative number in the result (only applicable to the conversion of eefgg)

Conversion Method:

'E', 'E' -- the result is formatted as a decimal number in the computer science notation.

'F' -- the result is formatted as a normal decimal representation.

'G', 'G' -- automatically selects the normal expression or scientific notation method based on the actual situation.

'A', 'A' -- the result is formatted as a hexadecimal floating point with valid digits and indexes.

3. format the characters:

It is very easy to format characters. C indicates the characters, and '-' indicates the left alignment in the logo. Nothing else.

4. format the percent sign:

After reading the preceding instructions, you will find that the percent sign "%" is a prefix in a special format. What should we do if we enter a percent sign? It must be escaped, but note that the escape character here is not "\", but "% ". In other words, the following statement can output "12% ":

System. Out. println (string. Format ("% 1 $ d %", 12 ));

5. Obtain the Independent Line Separator of the Platform:

System. getproperty ("line. separator") can be used to obtain independent row delimiters on the platform, but it is too cumbersome to use them in the format. Therefore, the format function comes with a platform-independent line separator, Which is string. Format ("% N ").

6. format the date type:

The following Date and Time conversion suffixes are defined for 'T' and 'T' conversion. These types are similar to but not exactly equivalent to those defined by GNU date and POSIX strftime (3C. Other conversion types are provided to access Java-specific functions (for example, using 'l' as the millisecond in seconds ).

Here are some practical examples of this method (the comment is the output result ):

Code:

Long Now = system. currenttimemillis ();

String S = string. Format ("% TR", now); // "15:12"

Code:

// Current month/day/year

Date d = new date (now );

S = string. Format ("% TD", d); // "07/13/04"

Code:

S = string. Format ("%, D", integer. max_value); // "2,147,483,647"

Code:

S = string. Format ("% 05d", 123); // "00123"

Is it very convenient and exciting? Haha, there are more results!

In fact, the format function is similar to the printf function in C language. Some format strings are similar to C, but some customization has been made to adapt to the Java language and some of these features have been used. This method supports layout alignment and arrangement, as well as regular formats of numeric values, strings, and date/time data, and output in a specific language environment. Supports common Java types such as byte, bigdecimal, and calendar.

Each method that generates formatted output requires the format string and parameter list. A format string is a string that can contain fixed text and one or more embedded format specifiers. Consider the following example:

Calendar c = ...; String S = string. Format ("Duke's birthday: % 1 $ TM % 1 $ te, % 1 $ ty", C );

The format string is the first parameter of the format method. It contains three format specifiers: "% 1 $ TM", "% 1 $ te", and "% 1 $ ty ", they indicate how parameters should be processed and where the text is inserted. The rest of the format string is fixed text that includes "Dukes birthday:" and any other space or punctuation. The parameter list consists of all parameters passed to the method after the format string. In the preceding example, the parameter list size is 1, which is composed of the new object calendar.

1. syntax for regular, character, and numeric format specifiers:

% [Argument_index $] [flags] [width] [. Precision] Conversion

The optional argument_index is a decimal integer used to indicate the position of a parameter in the parameter list. The first parameter is referenced by "1 $", the second parameter is referenced by "2 $", and so on.

The optional flags are character sets that modify the output format. The set of valid flag depends on the Conversion Type.

Optional width is a non-negative decimal integer, indicating the minimum number of characters to write to the output.

The optional precision is a non-negative decimal integer, which is usually used to limit the number of characters. The specific action depends on the Conversion Type.

The required conversion is a character that indicates how to format parameters. The valid conversion set of a given parameter depends on the Data Type of the parameter.

2. the syntax used to indicate format specifiers of Date and Time types is as follows:

% [Argument_index $] [flags] [width] Conversion

Optional argument_index, flags, and width are defined as the same.

The required conversion is a sequence of two characters. The first character is 'T' or 'T '. The second character indicates the format used. These characters are similar to but not completely equivalent to those defined by GNU date and POSIX strftime (3C.

3. syntax for format specifiers that do not correspond to parameters:

% [Flags] [width] Conversion

The optional flags and width definitions are the same as above.

The required conversion is a character that indicates the content to be inserted in the output.

Switch

Conversion can be divided into the following types:

1. General-applicable to any parameter type

2. Character-it can be applied to the basic types of Unicode characters: Char, character, byte, byte, short, and short. When character. isvalidcodepoint (INT) returns true, you can apply this conversion to int and integer types.

3. Value

1. integer-integer types that can be applied to Java: byte, byte, short, short, Int, integer, long, long, And biginteger

2. Floating Point-applicable to Java floating point types: float, float, Double, double, and bigdecimal

4. date/time-types that can be applied to Java and can be encoded for date or time: Long, long, calendar, and date.

5. Percentage-generate the nominal value '%' ('"u0025 ')

6. Line separator-generate a platform-specific line Separator

The following table summarizes the supported conversions. It consists of uppercase characters (such as 'B', 'h', 's', 'C', 'x', 'E', 'G', 'A', and 'T') the conversion of the representation is equivalent to the conversion of the corresponding lower-case characters, except for converting the result to the upper-case form according to the popular locale rules. The latter is equivalent to the following calls of string. touppercase.

Description of conversion parameter categories

'B', 'B'. If the ARG parameter is null, the result is "false ". If Arg is a Boolean value or Boolean, the returned string is string. valueof. Otherwise, the result is "true ".

'H', 'H'. If the ARG parameter is null, the result is "null ". Otherwise, the result is obtained by calling integer. tohexstring (Arg. hashcode.

'S', 'S'. If the ARG parameter is null, the result is "null ". If Arg implements formattable, Arg. formatto is called. Otherwise, the result is obtained by calling Arg. tostring.

'C', 'C' returns a Unicode Character

The 'd' integer is formatted as a decimal integer.

The 'O' integer is formatted as an octal integer.

'X', 'x' integer result is formatted as a hexadecimal integer

'E', 'E' floating point result is formatted as a decimal number expressed in the computer science notation

'F' the floating point result is formatted as a decimal number.

'G' and 'G' floating point are formatted in computer scientific notation or decimal format based on the value after precision and rounding.

'A', 'A' floating point result is formatted as a hexadecimal floating point number with valid digits and Indexes

The prefix of the 'T', 't' date/time Date and Time Conversion characters. See date/time conversion.

'%' Percentage result is the nominal value '%' ('"u0025 ')

The 'n' line separator result is a platform-specific line separator.

The hour in the 'H' 24-hour format is formatted as two digits with leading zeros (00-23) if necessary.

The hour in the 'I' 12-hour format is formatted as the two digits with the leading zero when necessary, that is, 01-12.

The hour in the 'K' 24-hour format, that is, 0-23.

Hours in the 'l' 12-hour format, that is, 1-12.

Minutes in the 'M' hour are formatted as two digits with leading zeros (00-59) if necessary.

Seconds in 's' minutes are formatted as two digits with leading zeros when necessary, that is, 00-60 ("60" is a special value required to support leap seconds ).

The millisecond in 'l' seconds is formatted as a three-digit number with leading zero when necessary, that is, 000-999.

The millisecond In 'n' seconds is formatted as the nine-digit number with the leading zero when necessary, that is, 000000000-999999999.

'P' indicates the language environment in lowercase in the morning or afternoon, for example, "am" or "PM ". You can use the conversion prefix 'T' to forcibly convert the output to an upper-case format.

The offset of 'Z' to the digital time zone in RFC 822 format of GMT, for example,-0800.

'Z' indicates a string in the abbreviated form of time zone. The formatter language environment replaces the parameter language environment (if any ).

The number of seconds since the Coordinated Universal Time (UTC) on January 1, 1970 00:00:00 to the present, that is, the difference between long. min_value/1000 and long. max_value/1000.

'Q' indicates the number of milliseconds that have elapsed since 00:00:00 on January 1, January 1, 1970 in Coordinated Universal Time (UTC), that is, the difference between long. min_value and long. max_value.

'B' is the full name of the month specific to the language environment, such as "January" and "February ".

'B' indicates the abbreviation of the month specific to the language environment, such as "Jan" and "FEB ".

'H' is the same as 'B.

'A is the full name of the day of the week specific to the language environment, such as "Sunday" and "Monday"

'A refers to the day of the week (such as "sun" and "mon") specific to the language environment"

'C' is divided by four digits of 100 to indicate the year. It is formatted as two digits with leading zeros (00-99) if necessary.

'Y' year, formatted as a four-digit (at least) with a leading zero when necessary, for example, 0092 equals 92 CE of the Gregorian calendar.

The last two digits of the 'y' year are formatted as the two digits with the leading zero when necessary, that is, 00-99.

The number of days in a year of 'J' is formatted as a three-digit number with a leading zero when necessary. For example, for a Gregorian calendar, the value is 001-366.

The 'M' month is formatted as a two-digit with a leading zero when necessary, that is, 01-13.

'D' the number of days in a month, which is formatted as the first zero or two digits (01-31) if necessary.

The number of days in a month is formatted as two digits, that is, 1-31.

'R' 24-hour time, formatted as "% TH: % TM"

The time in the 'T' 24-hour format is formatted as "% TH: % TM: % ts ".

'R' 12-hour time, formatted as "% Ti: % TM: % TS % TP ". The location marked in the morning or afternoon ('% TP') may be related to the language environment.

'D' date, formatted as "% TM/% TD/% ty ".

'F' complete date in ISO 8601 format, formatted as "% ty-% TM-% TD ".

'C' date and time, formatted as "% TA % TB % TD % TT % TZ % ty", for example, "Sun Jul 20 16:17:00 EDT 1969 ".

Marker general character integer floating point date/time Description

'-' Y the result is left aligned.

'#'Y1-Y3 y-the result should depend on the replacement form of the Conversion Type

'+'--Y4 y-the result always contains a symbol.

''--Y4 y-for positive values, the result will contain a leading space

'0'--y-the result will be filled with zero

','--Y2 Y5-the result will contain the group separator specific to the language environment

'('--Y4 Y5-the result will be a negative number enclosed in parentheses

Any character not explicitly defined as a conversion is invalid and is retained for future extension.

Date/time Conversion

The following Date and Time conversion suffixes are defined for 'T' and 'T' conversion. These types are similar to but not exactly equivalent to those defined by GNU date and posixstrftime (3C. Other conversion types are provided to access Java-specific functions (for example, using 'l' as the millisecond in seconds ).

The following Conversion characters are used to format the time:

The following Conversion characters are used to format the date:

The following Conversion characters are used to format common date/time combinations.

Any character not explicitly defined as a conversion is invalid and is retained for future extension.

Logo

The following table summarizes the supported labels. Y indicates that the flag is supported by the indicated parameter type.

1 depends on the formattable definition.

2 only applies to 'D' conversions.

3 is only applicable to conversion of 'o', 'x', and 'x.

4 when 'D', 'O', 'x', and 'X' are converted to biginteger, or 'D' conversion is applied to byte, byte, short, short, Int, integer, long, and long respectively.

5 is only applicable to conversion of 'E', 'E', 'F', 'G', and 'G.

Any character that is not explicitly defined as a flag is invalid and is retained for extension.

The width is the minimum number of characters that will be written to the output. The width is not applicable for line separator conversion. If the width is provided, an exception is thrown.

Precision is the maximum number of characters that will be written to the output for common parameter types.

For floating point conversions of 'E', 'E', and 'F', the precision is the number of digits after the decimal point separator. If the conversion is 'G' or 'G', the precision is the number of all digits of the obtained value after rounding. If the conversion is 'A' or 'A', you do not need to specify the precision.

Precision is not applicable to conversions of character, integer, date, time, percentage, and line separator. If precision is provided, an exception is thrown.

The parameter index is a decimal integer used to indicate the position of a parameter in the parameter list. The first parameter is referenced by "1 $", the second parameter is referenced by "2 $", and so on.

Another way to reference parameters by location is to use the '<' ('"u003c') flag, which will reuse the parameters with the previous format specifiers. For example, the following two statements produce the same characters:

Calendar c = ...; String S1 = string. format ("Duke's birthday: % 1 $ TM % 1 $ te, % 1 $ ty", c); string S2 = string. format ("Duke's birthday: % 1 $ TM % <$ te, % <$ ty", C );

 

Transferred from: China IT lab-Java Channel

Http://java.chinaitlab.com/net/878630.html

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.