Java string format – string Use of format()

This article introduces Java string formatting - string The usage of format() is as follows:

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.

test case

Output results

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

test case

Output results

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.

test case

Output results

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.

Output results

Compared with date format converter, time format converter is more and more accurate. It can format time into hours, minutes, seconds and even milliseconds. The converter for formatting the time string is shown in the figure.

Test code

Output results

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>