web123456

Introduction to the use of formatted splicing strings in Java

illustrate:
1. In JavaStringThe .format() method is aFormat stringThe method that allows developers to convert a set of data into strings of a certain format using a specific format
2. () is also a formatting function, but () uses standard placeholders, and the placeholders must specify parameter index, otherwise they cannot be formatted.

1. () Common formatting types:

Format Applicable Type illustrate
%s or %S String Format the output of the string
%d Integer Format the output of integers
%f floating point Format the output of floating point numbers
%t Date Type Format the output of date and time

If there are multiple parameters, it will start from 0 in turn. The following is a basic formatting example

2. Verification ()

1、String

  1. String testStr = "http://xxx:8080?a=%s&b=%s";
  2. String formatStr = String.format(testStr, "aa", "bb");
  3. ("formatStr = " + formatStr);

Output:

formatStr = http://xxx:8080?a=aa&b=bb

2. Integer

  1. String testStr = "http://xxx:8080?a=%d&b=%d";
  2. String formatStr = String.format(testStr, 1, 11);
  3. ("formatStr = " + formatStr);

Output:

formatStr = http://xxx:8080?a=1&b=11

3. Floating point type (decimal)

  1. String testStr = "http://xxx:8080?a=%.3f";
  2. String formatStr = String.format(testStr, 3.1415926);
  3. ("formatStr = " + formatStr);

Output:

formatStr = http://xxx:8080?a=3.142

illustrate:
(1) Floating point type needs to specify a decimal digit, such as %.2f or %.3f
(2), %, %.2f or %.3f respectively reserve 2 decimal places or 3 decimal places. The rounding rule is automatically used to retain decimal places.

4. Date type

  1. Date date = new Date();
  2. String dateStr = String.format("The current time is: %tF %tT", date, date);
  3. ("dateStr = " + dateStr);

Output:

dateStr =The current time is:2024-01-01 19:42:28

illustrate:
(1) In this example, we use two placeholders %tF and %tT, respectively, representing the date and time to format, respectively.
(2), %tF format date, such as: 2024-01-01
(3), %tT formatting time, such as: 19:42:28

5. Format the currency amount

  1. String testStr = "Selling price: ¥%.2f";
  2. String formatStr = String.format(testStr, 99.0);
  3. (formatStr);

Output:

Price: ¥99.00

3. Verification ()

1. Verify placeholders

  1. String testStr = "Test: {0},{1},{1},{3}";
  2. String formatStr = MessageFormat.format(testStr, "a", "b", "c", DateUtil.format(DateUtil.date(), DatePattern.NORM_DATETIME_PATTERN));
  3. (formatStr);

Output:

Test: a, b, b,2024-01-01 20:01:03

Judging from the output results, you can format the string, but you need to specify the parameter index used by the placeholder, and you can correctly obtain the corresponding parameter value based on the index.