Detailed usage of String.format()

1. Placeholder type

The letter following the placeholder "%" determines the type of actual parameter it accepts. The placeholder types are as follows:

insert image description here
Uppercase letters indicate that all letters in the output are uppercase.

We usually use %s, %d and %f the most, and occasionally use %t.

2. String and Integer Formatting

// 补齐空格并右对齐:
String.format("%10s, world", "Hello");     // 输出 "     Hello, world"
String.format("%8d", 123);                 // 输出 "     123"

// 补齐空格并左对齐:
String.format("%-10s, world", "Hello");    // 输出 "Hello     , world"
String.format("%-8d", 123);                // 输出 "123     "

// 补齐 0 并对齐(仅对数字有效)
String.format("%08d", 123);                // 输出 "00000123"
String.format("%-08d", 123);               // 错误!不允许在右边补齐 0

// 输出最多N个字符
String.format("%.5s", "Hello, world");       // 输出 "Hello"
String.format("%.5s...", "Hello, world");    // 输出 "Hello..."
String.format("%10.5s...", "Hello, world");  // 输出 "     Hello..."

// 输出逗号分隔数字
String.format("%,d", 1234567);               // 输出 "1,234,567"

3. Date formatting

This is a little more complicated, but if you want to mix text numbers and dates in strings, it should be more convenient to use only one method than combining DateFormat and NumberFormat.

First add a piece of knowledge, that is, the placeholder can specify a parameter at a certain position, and the format is %n . For example. e.g. %2. For example, d represents the second integer parameter. Note that n here starts with 1 instead of 0.

When formatting a date, multiple placeholders are required to point to the same parameter (to avoid repeating the same parameter several times), and because "t" means date and time, the complete format is %n$tX, where X means to take what part of the time. Optional values ​​for X such as: Y=year; m=month; d=day; H=hour; M=minute; S=second; L=millisecond; A=day of the week (name); B=month name;
and other letters.

	// 输出格式为 “Now is         15:04:52, 星期日”
	// 注意 "%1$10tH" 中的 10 同样表示空格补齐 10 位并右对齐
	String.format("Now is %1$10tH:%1$tM:%1$tS, %1$tA", new Date())

Guess you like

Origin blog.csdn.net/weixin_45336946/article/details/128724789