JAVA string formatting - use of String.format()

Formatting of general types

The format() method of the String class is used to create a formatted String and connect multiple String objects. Students familiar with C language should remember the sprintf() method of C language. They have similarities. The format() method has two overloaded forms.
format(String format, Object... args) the new string uses the local language environment to formulate string format and parameters to generate a formatted new string.

Format (locale, locale, string format, object... args) uses the specified locale to formulate string formats and parameters to generate formatted strings.

Display different conversion characters to realize the conversion from different data types to strings, as shown in the figure.

Conversion characterexplainExample
%sString type"mingrisoft"
%cCharacter type'm'
%bBoolean typetrue
%dInteger type (decimal)99
%xInteger type (HEX)FF
%oInteger type (octal)seven 7
%fFloating point type99.99
%aHexadecimal floating point typeFF.35AE
%eIndex type9.38e+5
%gUniversal floating point type (shorter of f and e types)
%hHash code
%%Percentage type
%nNewline character
%txDate and time type (x for different date and time converters)

test case

public static void main(String[] args) {
	    String str=null;
	    str=String.format("Hi,%s", "distinguished linguist and strong supporter of language reform");
	    System.out.println(str);
	    str=String.format("Hi,%s:%s.%s", "Wang Nan","distinguished linguist and strong supporter of language reform","Wang Zhang");          
	    System.out.println(str);                         
	    System.out.printf("letter a The upper case is:%c %n", 'A');
	    System.out.printf("3>7 The results are:%b %n", 3>7);
	    System.out.printf("100 Half of them are:%d %n", 100/2);
	    System.out.printf("100 The hexadecimal number of is:%x %n", 100);
	    System.out.printf("100 The octal number of is:%o %n", 100);
	    System.out.printf("50 The book is 8 yuan.5 The discount is:%f element%n", 50*0.85);
	    System.out.printf("The hexadecimal number of the above price is:%a %n", 50*0.85);
	    System.out.printf("The above price index indicates:%e %n", 50*0.85);
	    System.out.printf("The shorter length of the above price index and floating point number results is:%g %n", 50*0.85);
	    System.out.printf("What's the discount above%d%% %n", 85);
	    System.out.printf("letter A The hash code for is:%h %n", 'A');
}

Output results

Hi,distinguished linguist and strong supporter of language reform
Hi,Wang Nan:distinguished linguist and strong supporter of language reform.Wang Zhang
 letter a The upper case is: A 
3>7 The results are: false 
100 Half is: 50 
100 The hexadecimal number of is 64 
100 The octal number of is 144 
50 The book is 8 yuan.5 The discount is: 42.500000 element
 The hexadecimal number of the above price is: 0 x1.54p5 
The above price index indicates: 4.250000e+01 
The length of the index and floating point number results of the above price is 42.5000 
The discount above is 85% 
letter A The hash code is: 41 

Match the sign of the conversion character, as shown in the figure.

SignexplainExampleresult
+Sign positive or negative numbers("%+d",15)+15
Align left("%-5d",15)15
0Add 0 before the number("%04d", 99)0099
SpaceAdds a specified number of spaces before an integer("% 4d", 99)99
,Group numbers with ","("%,f", 9999.99)9,999.990000
(Use parentheses to contain negative numbers("%(f", -99.99)(99.990000)
#If it is a floating-point number, the decimal point is included, and if it is hexadecimal or octal, 0x or 0 is added("%#x", 99)("%#o", 99)0x63 0143
<Format the parameters described by the previous converter('% 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("Format parameters $Use of:%1$d,%2$s", 99,"abc");           
	    System.out.println(str);                     
	    //+Use
	    System.out.printf("Symbols showing positive and negative numbers:%+d And%d%n", 99,-99);
	    //Supplement O use
	    System.out.printf("The best number is:%03d%n", 7);
	    //Space use
	    System.out.printf("Tab The effect of the key is:% 8d%n", 7);
	    //. use
	    System.out.printf("The effect of integer grouping is:%,d%n", 9989997);
	    //Space and number after decimal point
	    System.out.printf("The price of a book is:% 50.5f element%n", forty-nine.8)
}

Output results

Format parameters $Use of: 99,abc
 Symbols showing positive and negative numbers:+99 And-99
 The best number is 007
Tab The effect of the key is:       7
 The effect of integer grouping is: 9,989,997
 The price of a book is:                      49.80000 element

Date and event string formatting
It is often necessary to display time and date in the program interface, but the display format is often unsatisfactory. It is necessary to write a lot of code and obtain the ideal date and time format through various algorithms. There is also a% tx converter in the string format, which is not described in detail. It is specially used to format the date and time.% n The x in the tx converter represents another converter for processing date and time format, and their combination can format the date and time into a variety of formats.

The format of common date and time combinations is shown in the figure.

Conversion characterexplainExample
cInclude all date and time informationSaturday October 27 14:21:20 CST 2007
F"Year Month Day" format2007-10-27
D"Month / day / year" format10/27/07
r"HH:MM:SS PM" format (12 hour system)02:25:51 PM
T"HH:MM:SS" format (24 hour system)14:28:16
R"HH:MM" format (24 hour system)14:28

test case

public static void main(String[] args) {
		    Date date=new Date();                                
		    //c. use of
		    System.out.printf("All date and time information:%tc%n",date);        
		    //Use of f
		    System.out.printf("year-month-Daily format:%tF%n",date);
		    //d) use of
		    System.out.printf("month/day/Year format:%tD%n",date);
		    //Use of r
		    System.out.printf("HH:MM:SS PM Format (12 hour system):%tr%n",date);
		    //Use of t
		    System.out.printf("HH:MM:SS Format (24 hour system):%tT%n",date);
		    //Use of R
		    System.out.printf("HH:MM Format (24 hour system):%tR",date);
}

Output results

Full date and time information: Monday September 10:43:36 CST 2012
 year-month-Daily format: 2012-09-10
 month/day/Year format: 09/10/12
HH:MM:SS PM Format (12 hour system): 10:43:36 morning
HH:MM:SS Format (24 hour system): 10:43:36
HH:MM Format (24 hour system): 10:43

Defining the date format converter enables the date to 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, abbreviation of month
	    String str=String.format(Locale.US,"English month abbreviation:%tb",date);     
	    System.out.println(str);                                                                            
	    System.out.printf("Local month abbreviation:%tb%n",date);
	    //Use of B, full name of month
	    str=String.format(Locale.US,"Full name of English month:%tB",date);
	    System.out.println(str);
	    System.out.printf("Full name of local month:%tB%n",date);
	    //Use of a, abbreviation of week
	    str=String.format(Locale.US,"Abbreviation of English Week:%ta",date);
	    System.out.println(str);
	    //Use of A, full name of the week
	    System.out.printf("Abbreviation of local week:%tA%n",date);
	    //The use of C, the first two years
	    System.out.printf("The first two digits of the year (fill 0 in front of less than two digits):%tC%n",date);
	    //Use of y, the last two years
	    System.out.printf("The last two digits of the year (fill 0 in front of less than two digits):%ty%n",date);
	    //Use of j, number of days in a year
	    System.out.printf("Number of days in a year (i.e. the day of the year):%tj%n",date);
	    //Use of m, month
	    System.out.printf("Month with two digits (fill 0 in front of less than two digits):%tm%n",date);
	    //d use, day (two digits, not enough to fill zero)
	    System.out.printf("Two digit day (fill 0 in front of less than two digits):%td%n",date);
	    //Use of e, day (one digit does not fill in zero)
	    System.out.printf("Day of the month (0 is not added in front):%te",date);
}

Output results

English month abbreviation: Sep
 Local month abbreviation: September
 Full name of English month: September
 Full name of local month: September
 Abbreviation of English Week: Mon
 Abbreviation of local week: Monday
 The first two digits of the year (fill 0 in front of less than two digits): 20
 The last two digits of the year (fill 0 in front of less than two digits): 12
 Number of days in a year (i.e. the day of the year): 254
 Month with two digits (fill 0 in front of less than two digits): 09
 Two digit day (fill 0 in front of less than two digits): 10
 Day of month (no 0 in front): 10

Tags: Java Back-end

Posted on Thu, 21 Oct 2021 22:33:30 -0400 by Jackanape