Use of java String.format()

General type formatting

The format() method of the String class is used to create formatted strings and connect multiple string objects.Students who are familiar with C should remember the sprintf() method in C, which has similarities.The format() method has two forms of overload.

Form (String format, Object... args) The new string uses the local language environment, formatting the string and generating the new formatted string with parameters.

Form (Locale locale, String format, Object... args) uses the specified locale to format strings and generate formatted strings with parameters.

Show different converters to convert different data types to strings, as shown in the figure.

Converter Explain 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 Index type 9.38e+5
%g Universal floating point type (shorter of f and e types)
%h Hash code
%% Percentage type
%n Line Break
%tx Date and time type (x stands 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 Uppercase is:%c %n", 'A');
	    System.out.printf("3>7 The result is:%b %n", 3>7);
	    System.out.printf("100 Half of them are:%d %n", 100/2);
	    System.out.printf("100 The hexadecimal number is:%x %n", 100);
	    System.out.printf("100 The octal number of the is:%o %n", 100);
	    System.out.printf("50 Book type8 in Yuan.5 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 index of the above price indicates:%e %n", 50*0.85);
	    System.out.printf("The exponential and floating point results of the above price have a shorter length:%g %n", 50*0.85);
	    System.out.printf("The discount above is%d%% %n", 85);
	    System.out.printf("Letter A The hash code for is:%h %n", 'A');
	}

Output Results

Hi, Wang Li
 Hi, Wang Nan: Wang Li. Wang Zhang
 The capital letter a is: 
The result of 3>7 is: false 
Half of 100 is:50 
The hexadecimal number of 100 is:64 
The octal number of 100 is 144 
A discount of 8.5 for 50 yuan books is 42.500000 yuan
 The hexadecimal number of the above price is: 0x1.54p5 
The index of the above price indicates: 4.250000e+01 
The index and floating point results of the above price are shorter: 42.5000 
The discount above is 85% 
The hash code for letter A is:41 
Match the marker for the converter as shown in the figure.
Sign Explain Example Result
+ Add symbols for positive or negative numbers ("%+d",15) +15
Left Alignment ("%-5d",15) |15 |
0 Number preceded by 0 ("%04d", 99) 0099
Spaces Add a specified number of spaces before an integer ("% 4d", 99) | 99|
, Grouping numbers by',' ("%,f", 9999.99) 9,999.990000
( Use parentheses to include negative numbers ("%(f", -99.99) (99.990000)
# If floating point number contains decimal point, if hexadecimal or octal add 0x or 0 ('%#x', 99) and ('%#o', 99) 0x63 and 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:%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);
	    //Supplemental O Use
	    System.out.printf("The cattle 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 grouping integers is:%,d%n", 9989997);
	    //Spaces and Number After Decimal Point
	    System.out.printf("The price of a Book is:% 50.5f element%n", 49.8);
	}

Output Results

Use of format parameter $99,abc
 Symbols showing positive and negative numbers: +99 and -99
 The cattle number is: 007
 The effect of the Tab key is:7
 The effect of grouping integers is: 9,989,997
 The price of a book is 49.80000 yuan

Date and Event String Formatting Time and date are often required to be displayed in the program interface, but their display format is often unsatisfactory. A lot of code needs to be written to get the ideal date and time format through various algorithms.There is also a%tx converter in the string format that is not described in detail and is designed to format dates and times.The x in the%tx converter represents another converter that processes date and time formats, and their combination formats date and time into multiple formats.

Common date and time combinations are formatted as shown in the figure.

Converter Explain Example
c Include all date and time information Saturday June 27th 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-time) 02:25:51 PM
T "HH:MM:SS" format (24-time) 14:28:16
R "HH:MM" format (24-time) 14:28

test case

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

Output Results

Full date and time information: Monday September 10:43:36 CST 2012
 Year-month-day format: 2012-09-10
 Month/day/year format: 09/10/12
 HH:MM:SS PM format (12 hours): 10:43:36 am
 HH:MM:SS format (24-time): 10:43:36
 HH:MM format (24-time): 10:43

Converters that define the date format enable the date to generate a new string with the specified converter.These date converters.

		public static void main(String[] args) {
		    Date date=new Date();                                    
		    //Use of b, short for month
		    String str=String.format(Locale.US,"English month for short:%tb",date);     
		    System.out.println(str);                                                                            
		    System.out.printf("Local month for short:%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, short for week
		    str=String.format(Locale.US,"Short form of English week:%ta",date);
		    System.out.println(str);
		    //Use of A, full name of week
		    System.out.printf("Short for local week:%tA%n",date);
		    //C, two years ago
		    System.out.printf("The first two digits of the year (less than two leading zeros):%tC%n",date);
		    //y use, two years later
		    System.out.printf("Two digits after the year (less than two leading zeros):%ty%n",date);
		    //Use of j, days of year
		    System.out.printf("Number of days in a year (that is, the day of the year):%tj%n",date);
		    //Use of m, month
		    System.out.printf("Two-digit month (less than two preceding zeros):%tm%n",date);
		    //d use, day (binary, not enough to make up for zero)
		    System.out.printf("Two-digit days (less than two leading zeros):%td%n",date);
		    //Use of e, day (one non-zero)
		    System.out.printf("Date of month (not preceded by 0):%te",date);
		}

Output Results

English month for short: Sep
 Local month for short: September
 Full name of English month: September
 Full name of local month: September
 Short form of English week: Mon
 Short for local week: Monday
 The first two digits of the year (less than two leading zeros):20
 Two digits after the year (less than two leading zeros):12
 Days in a year (that is, the day of the year): 254
 Two-digit month (less than two preceding zeros):09
 Two-digit days (less than two leading zeros):10
 Date of month (not preceded by 0): 10
 More and more precise time format converters than date format converters.It can format time into units such as hours, minutes, seconds and even milliseconds.The converter that formats the time string is shown in the figure.
Converter Explain Example
H 2-digit 24-hour hours (less than 2 digits preceded by 0) 15
I Hours of 2-digit 12-hour duration (less than 2 digits preceded by 0) 03
k 2-digit 24-hour hour hour (no 0 before) 15
l 2-digit 12-hour hour hour (no 0 before) 3
M Minutes with 2 digits (less than 0 before 2 digits) 03
S 2-digit seconds (less than 2 digits preceded by 0) 09
L 3-digit milliseconds (less than 3 digits preceded by 0) 015
N Milliseconds of 9 digits (less than 9 digits preceded by 0) 562000000
p Morning or afternoon markers for lower case letters Chinese: afternoon English: pm
z Offset from RFC822 time zone of GMT +0800
Z Time Zone Abbreviation String CST
s Seconds elapsed since 1970-1-100:00:00 1193468128
Q Milliseconds elapsed since 1970-1:00:00 1193468128984

Test Code

	public static void main(String[] args) {
		Date date = new Date();
		//Use of H
		System.out.printf("2 Number 24 hours (less than 2 digits preceded by 0):%tH%n", date);
		//Use of I
		System.out.printf("2 Hours with 12 digits (less than 2 digits preceded by 0):%tI%n", date);
		//Use of k
		System.out.printf("2 Numeric 24-hour hours (no 0 before):%tk%n", date);
		//Use of l
		System.out.printf("2 Hours of 12-digit hours (no zeros before):%tl%n", date);
		//Use of M
		System.out.printf("2 Minutes with digits (0 before less than 2 digits):%tM%n", date);
		//Use of S
		System.out.printf("2 Number of seconds (less than 2 digits preceded by 0):%tS%n", date);
		//Use of L
		System.out.printf("3 Milliseconds of digits (less than 3 digits preceded by 0):%tL%n", date);
		//Use of N
		System.out.printf("9 Milliseconds of digits (less than 9 digits preceded by 0):%tN%n", date);
		//Use of p
		String str = String.format(Locale.US, "Morning or afternoon markers for lower case letters(Britain): %tp", date);
		System.out.println(str); 
		System.out.printf("Small letter morning or afternoon markers (in):%tp%n", date);
		//Use of z
		System.out.printf("Be relative to GMT Of RFC822 Offset of time zone:%tz%n", date);
		//Use of Z
		System.out.printf("Time Zone Abbreviation String:%tZ%n", date);
		//Use of s
		System.out.printf("1970-1-1 00:00:00 The number of seconds that have elapsed so far:%ts%n", date);
		//Use of Q
		System.out.printf("1970-1-1 00:00:00 The number of milliseconds that have elapsed so far:%tQ%n", date);
	}

Output Results

2-digit 24-hour hours (less than 2 digits before 0):11
 Two-digit 12-hour hour hour (less than 2 digits preceded by 0):11
 2-digit 24-hour hour hour (no 0 before): 11
 2-digit 12-hour hour hour (no 0 before): 11
 Minutes with 2 digits (0 before less than 2 digits):03
 2-digit seconds (less than 2 digits preceded by 0):52
 3-digit milliseconds (less than 3 digits preceded by 0): 773
 9-digit milliseconds (less than 9 digits preceded by 0): 773000000
 Small letter morning or afternoon marker (English):am
 Small letter morning or afternoon marker (mid): morning
 Offset from RFC822 time zone of GMT: +0800
 Time zone abbreviation string: CST
 Seconds elapsed since 1970-1:00:00: 1347246232
 Milliseconds elapsed since 1970-1:00:00: 1347246232773

re:https://blog.csdn.net/qq_40220804/article/details/81190122

Tags: Programming less

Posted on Thu, 14 May 2020 23:07:01 -0400 by Nommy