JAVA string formatting - the use of String.format() and MessageFormat

String.format() Formatting


of general types The format() method of the String class is used to create formatted strings and concatenate multiple string objects. Students familiar with C language
should remember the sprintf() method of C language, the two are similar. The format() method has two overloads.
format(String format, Object... args) New String Generates
a .
format(Locale locale, String format, Object... args) Generates a formatted string using the specified locale, specifying the string format and
arguments .
Display different converters to convert different data types to strings, as shown in the figure.
Conversion Character Description Example

%s String type "mingrisoft"
%c Character type 'm'
%b Boolean type true

%d Integer type (decimal) 99

%x Integer type (hexadecimal) FF

%o Integer type (octal) 77

%f Floating point type 99.99

%a Hexadecimal floating point type FF.35AE

%e Exponent type 9.38e+5

%g Generic floating point type (the shorter of f and e)
  
%h Hash code
  
%% Percentage type %

%n Line break
  
%tx Date and time type (x represents different date and time converters
Attribute value example
%n$ms: represents the output is a string, n represents the first Several parameters, setting the value of m can place a space before the output
%n$md: represents the output is an integer, n represents the number of parameters, setting the value of m can place a space before the output, or it
can be set to 0m, Place m 0
%n$mf before the output: it means that the output is a floating point number, and n represents the number of parameters. Setting the value of m can control the number of decimal places. For example
, when m=2.2, the output format is 00.00.
It can also be simple written as:
%d (integer)
%f (float)
%s (string)
  
test case
public static void main(String[] args) {
     String str=null;
     str=String.format("Hi,%s" , "Wang Li");
     System.out.println(str);
     str=String.format("Hi,%s:%s.%s", "Wang Nan","Wang Li","Wang Zhang") ;         
     System.out.println(str);                        
     System.out.printf("The uppercase of the letter a is: %c %n", 'A');
     System.out.printf("The result of 3>7 is: %b %n", 3>7);
     System.out.printf("Half of 100 is: %d %n", 100/2);
     System.out.printf("The hexadecimal number of 100 is: %x % n", 100);
     System.out.printf("The octal number of 100 is: %o %n", 100);
     System.out.printf("The discount of 8.5 yuan for a book of 50 yuan is: %f yuan%n", 50*0.85);
     System.out.printf("The hexadecimal number of the above price is: %a %n", 50*0.85);
     System.out.printf("The index of the above price is: %e %n", 50*0.85) ;
     System.out.printf("The length of the exponent and floating point result of the above price is shorter: %g %n",
50*0.85);
     System.out.printf("The discount above is %d%% % n", 85);
     System.out.printf("The hash code of letter A is: %h %n", 'A');
}
Output result
Hi, Wang Li
Hi, Wang Nan: Wang Li. Wang Zhang Letter
The capitalization of a is: A
The result of 3>7 is: false
The half of 100 is: 50
The hexadecimal number of 100 is: 64
The octal number of 100 is: 144
The 8.5 discount for the book of 50 yuan is: 42.500000 yuan
Above The hexadecimal number of the price is: 0x1.54p5
The index of the price above: 4.250000e+01
The index of the price above and the length of the floating point number result are shorter: 42.5000
The discount above is 85%
The hash code of the letter A is : 41

with the symbol of the converter, as shown in the figure.
Flag Description Example Result

+ Add sign for positive or negative numbers ("%+d",15) +15

− Left justify ("%-5d",15) |15 |

0 Number with 0 in front of it ("%04d", 99 ) 0099

spaces adds a specified number of spaces before integers ("% 4d", 99) | 99|

, groups numbers with "," ("%,f", 9999.99) 9,999.990000

(uses parentheses to include negative numbers ("%(f ", -99.99) (99.990000)

# Include decimal point if float, ("%#x", 99) 0x63
          if hex or octal add 0x or 0 ("%#o", 99) 0143

< Format the argument described by the previous switch ("%f and %<3.2f", 99.45) 99.450000 and 99.45

$ formatted parameter index ("%1$d,%2$s", 99,"abc") 99,abc

test case
public static void main(String[] args) {
     String str=null;
     //$ Use
     str=String.format("Use of format parameter $:%1$d,%2$s", 99,"abc");          
     System.out.println(str);                    
     //+Use
     System.out.printf ("Display the sign of positive and negative numbers: %+d and %d%n", 99,-99);
     //Use
     System.out.printf("The best number is: %03d%n", 7 );
     //Use
     System.out.printf("The effect of Tab key is: % 8d%n", 7);
     //. Use
     System.out.printf("The effect of integer grouping is: %,d%n ", 9989997);
     //Number of spaces and decimals
     System.out.printf("The price of a book is: % 50. 5f yuan%n", 49.8);
}
output result
The use of the format parameter $: 99, abc
shows the sign of positive and negative numbers: +99 and -99
The best number is: 007
The effect of the Tab key is: 7
The effect of the integer grouping is: 9,989,997
The price of a book is: 49.80000 Meta

Date and Event String Formatting
Time and date are often required to be displayed in the program interface, but the displayed format is often unsatisfactory, and a lot of
code to obtain the ideal date and time format through various algorithms. There is also the %tx conversion character in the string format, which is not described in detail
, it is specially used to format date and time. The x in the %tx converter represents additional
converters , and their combination can format dates and times into multiple formats.
Formats for common date and time combinations, as shown.
Converter Description Example

c Include all date and time information Sat Oct 27 14:21:20 CST 2007

F "Year-Month-Day" format 2007-10-27

D "Month/Day/Year" format 10/27/07

r “HH:MM:SS PM” format (12:00) 02:25:51 PM

T “HH:MM:SS” format (24:00) 14:28:16

R “HH:MM” format (24:00) System.out.printf   ( "All       date                                and       time information: %

tc       %n", date);              //f uses       System.out.printf("year-month-day format: %tF%n",date);       //d uses       System.out.printf("month/day/year format: %tD%n",date);       //r uses       System.out.printf("HH:MM:SS PM format (12-hour system): %tr%n",date);       //t uses       System. out.printf("HH:MM:SS format (24-hour system): %tT%n",date);












      //R use
      System.out.printf("HH:MM format (24-hour system): %tR", date);
  }
Output result
All date and time information: Monday September 10 10:43:36 CST 2012
Year-Month-Day Format : 2012-09-
Oct/Day/Year Format: 09/10/12
HH:MM:SS PM Format (12:00): 10:43:36 AM
HH:MM:SS Format ( 24-hour time):
10:43:36 HH:MM format (24-hour time): 10:43
The converter that defines the date format can make the date generate a new string through the specified converter. These date converters are shown in the figure
.
  public static void main(String[] args) {
      Date date=new Date();                                   
      //Use of b, month abbreviation
      String str=String.format(Locale.US,"English month abbreviation:%tb",date);    
      System.out.println(str);                                                              
           
      System.out.printf("Local month abbreviation: %tb%n",date);
      //The use of B, the full name of the month
      str=String.format(Locale.US,"the full name of the English month: %tB",date);
      System.out.println(str);
      System.out.printf("The full name of the local month: %tB%n",date);
      //Use of a, week abbreviation
      str=String.format(Locale.US,"English week abbreviation: %ta",date);
      System.out.println(str);
      / The use of /A, the full name of the week
      System.out.printf("The abbreviation of the local week: %tA%n",date);
      //The use of C
      , the first two digits System.out.printf("The first two digits of the year Numbers (fill with 0 in front of less than two digits): %tC%
n", date);
      //Use of y,
      two digits after the year System.out.printf("The last two digits of the year (fill with 0 in front of less than two digits) :%ty%
n",date);
      //The use of j, the number of days in a
      year System.out.printf("The number of days in a year (that is, the day of the year):%tj%n",date);
      // use of m, month
      System.out.printf("The month with two digits (with 0 in front of less than two digits): %tm%
n", date);
      //The use of d, day (two digits, not enough zeros)
      System.out.printf ("The day with two digits (the less than two digits are filled with 0): %td%
n", date);
      //The use of e, the day (one digit is not filled with zeros)
      System.out.printf("The day of the month ( Do not add 0 in front): %te",date);
  }
Output result
English month abbreviation: Sep
Local month abbreviation: September Full
English month name: September
Local month full name: September
English week abbreviation: Mon
Local week abbreviation: Week The first two digits of a
year (less than two digits are filled with 0):
the last two digits of 20 years (less than two digits are filled with 0): 12
The number of days in the year (that is, the first day of the year): 254
two digits The month of the number (with 0 in front of less than two digits): 09
The day with two digits (with 0 in front of less than two digits):
the day of October (without 0 in front of it): 10
Compared with the date format converter, the time format Conversions are more and more precise. It can format time into hours, minutes,
seconds and even hours and milliseconds. The converters for formatting time strings are shown in the figure.
Conversion Symbol Description Example

H 2-digit 24-hour hour (if less than 2 digits are filled with 0 in front) 15

I 2-digit 12-hour hour (if less than 2 digits are filled with 0 in front) 03

k 2-digit 24-hour hour ( No leading zeros) 15

l 2-digit 12-hour hour (no leading zeros) 3

M two-digit minutes (less than two leading zeros) 03

S two-digit seconds (less than two leading zeros) ) 09

L 3-digit millisecond (less than 3 digits filled with 0 in front) 015

N 9-digit millisecond (less than 9 digits filled with 0 before) 562000000

p am or pm mark of lowercase letters 中:pm English: pm

z relative to Offset of RFC822 time zone from GMT + 0800

Z Time zone abbreviation string CST

s 1970-1-1 00:00:00 The number of seconds elapsed till now 1193468128

Q 1970-1-1 00:00:00 The number of milliseconds elapsed till now 1193468128984

Test code
public static void main(String[] args) {
  Date date = new Date();
  //H's use
  System.out.printf("2-digit 24-hour hour (less than 2 digits with 0 in front):%tH%n",
date);
  //I The use of
  System.out.printf("2-digit 12-hour hour (less than 2 digits are filled with 0): %tI%n",
date);
  //k's use of
  System.out.printf("2 digits 24-hour hour (do not add 0 in front):%tk%n", date);
  //l use
  System.out.printf("2-digit 12-hour hour (do not add 0 in front):%tl %n", date);
  //M's use
  System.out.printf("2-digit minute (less than 2 digits with 0 in front):%tM%n", date);
  //S's use
  System.out .printf("Seconds with 2 digits (less than 2 digits with 0 in front): %tS%n", date);
  //L's use
  System.out.printf("3-digit milliseconds (less than 3 digits are filled with 0):%tL%n", date);
  //N's use
  System.out.printf("9-digit number The number of milliseconds (with 0 in front of less than 9 digits): %tN%n", date);
  //Use of p
  String str = String.format(Locale.US, "Morning or afternoon marking of lowercase letters (English):
% tp", date);
  System.out.println(str);
  System.out.printf("The morning or afternoon mark of lowercase letters (middle): %tp%n", date);
  //Use of z
  System.out .printf("The offset of the RFC822 time zone relative to GMT:%tz%n", date);
  //The use of Z
  System.out.printf("Time zone abbreviation string:%tZ%n", date);
  //S's use
  System.out.printf("1970-1-1 00:00:00 The number of seconds elapsed until now: %ts%n",
date);
  //Q's use
  System.out.printf( "1970-1-1 00:00:00 milliseconds since: %tQ%n",
date);
}
output result
2-digit 24-hour hour (less than 2 digits filled with 0): 11
2-digit 12-hour hour (less than 2 digits filled with 0): 11
2-digit 24-hour hour (without preceding 0) :11
2-digit 12-hour hour (without leading 0): 11
2-digit minute (less than 2 digits with 0 before): 03
2-digit second (less than 2 with 0 before): 52
3-digit Number milliseconds (less than 3 digits preceded by 0): 773
9-digit milliseconds (less than 9 digits preceded by 0): 773000000
lowercase morning or afternoon mark (English): am
lowercase morning or afternoon mark (in ):
AM Offset from GMT's RFC822 time zone: +0800
Time zone abbreviation String: CST
1970-1-1 00:00:00 Seconds elapsed now: 1347246232 1970-1-1
00:00: 00 The number of milliseconds since: 1347246232773


MessageFormat


MessageFormat provides a language-independent way to generate connection messages. Use this method to construct a message to display to the end user.
MessageFormat takes an array of objects, formats those objects, and inserts the formatted string into the pattern at the appropriate location.
Note: MessageFormat differs from other Format classes because MessageFormat objects are created using one of its constructors (rather than using a getInstance-style factory method). The factory method is not necessary because MessageFormat itself does not implement locale-specific behavior. Locale-specific behavior is defined by the provided schema and subformats for inserted parameters.
Usage Information Some usage examples are given
below . Of course, in an actual internationalizer, the message format patterns and other static strings will be taken from the resource bundle. Other parameters are determined dynamically at runtime.
The first example uses the static method MessageFormat.format, which internally creates a MessageFormat that is only used once:
int planet = 7;
String event = "a disturbance in the Force";
String result = MessageFormat.format(
     "At {1 ,time} on {1,date}, there was {2} on planet {0,number,integer}.",
     planet, new Date(), event);
output:
At 12:30 PM on Jul 3, 2053 , there was a disturbance in the Force on planet 7.
The following example creates a reusable MessageFormat instance:
int fileCount = 1273;
String diskName = "MyDisk";
Object[] testArgs = {new Long(fileCount), diskName};
MessageFormat form = new MessageFormat(
     "The disk \"{1}\" contains {0} file(s).");
System.out.println(form.format(testArgs));
Output for different fileCount values:
The disk "MyDisk" contains 0 file(s).
The disk "MyDisk" contains 1 file(s).
The disk "MyDisk" contains 1,273 file(s).
For more complex patterns, ChoiceFormat can be used to generate the correct singular and plural forms:
MessageFormat form = new MessageFormat("The disk \"{1}\" contains {0}.");
double[ ] filelimits = {0,1,2};
String[] filepart = {"no files","one file","{0,number} files"};
ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
form.setFormatByArgumentIndex(0, fileform);
int fileCount = 1273;
String diskName = "MyDisk";
Object[] testArgs = {new Long(fileCount), diskName};
System.out.println(form.format(testArgs));
Output for different fileCount values:
The disk "MyDisk" contains no files.
The disk "MyDisk" contains one file.
The disk "MyDisk" contains 1,273 files. The
ChoiceFormat can be created programmatically, as in the example above, or using the pattern create. For more information, see ChoiceFormat.
form.applyPattern(
    "There {0,choice,0#are no files|1#is one file|1<are {0,number,integer} files}.");
Note: As you can see from the above example, by Strings generated by ChoiceFormat in MessageFormat are subject to special handling; '{' Occurrences are used to indicate subformats and cause recursion. If both MessageFormat and ChoiceFormat are created programmatically (rather than using string patterns), be careful not to generate formats that recurse on themselves, which would result in an infinite loop.
When an argument is parsed multiple times in a string, the last match will be the final result of the parsing. For example,
MessageFormat mf = new MessageFormat("{0,number,#.##}, {0,number,#.#}");
Object[] objs = {new Double(3.1415)};
String result = mf. format( objs );
// result now equals "3.14, 3.1"
objs = null;
objs = mf.parse(result, new ParsePosition(0));
// objs now equals {new Double(3.1)}
Again, use contains Patterns with multiple matches of the same argument parsed against a MessageFormat object will return the last match. For example,
MessageFormat mf = new MessageFormat("{0}, {0}, {0}");
String forParsing = "x, y, z";
Object[] objs = mf.parse(forParsing, new ParsePosition(0) );
// result now equals {new String("z")}
synchronous The
message format is not synchronous. It is recommended to create separate format instances for each thread. If multiple threads access a format at the same time, it must be externally synchronized.
The static method is generally used to format strings
static String format(String pattern, Object... arguments)
          creates a MessageFormat with the given pattern and uses it to format the given arguments.
public static String format(String pattern,
                            Object... arguments) Creates a MessageFormat with the given pattern and uses it to format the given arguments. This is equivalent to
(new MessageFormat(pattern)).format(arguments, new StringBuffer(), null).toString()
throws:
IllegalArgumentException - if the pattern is invalid, or the arguments in the arguments array are not the format elements expected using that argument type.

Reprinted from: http://blog.csdn.net/mike_caoyong/article/details/36694775

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326489223&siteId=291194637