printf格式化字符串

We’ve already discussed Java println() method in a previous tutorial. Today, we’ll discuss the printf() method and its various implementations in detail. Ready. Get. Set. Go!

在上一教程中,我们已经讨论过Java println()方法。 今天,我们将详细讨论printf()方法及其各种实现。 准备。 得到。 组。 走!

Java printf()

  • printf()方法不仅在C语言中,而且在Java中。
  • 此方法属于PrintStream类。
  • 它用于使用各种格式说明符打印格式化的字符串。

句法

(Java printf()

  • printf() method is not only there in C, but also in Java.
  • This method belongs to the PrintStream class.
  • It’s used to print formatted strings using various format specifiers.

Syntax

)

Following are the syntaxes available for the printf() method:

以下是可用于printf()方法的语法:

System.out.printf(string);
System.out.printf(format, arguments);
System.out.printf(locale, format, arguments);

The first one does not do any formatting though and it’s like the println() method.

第一个虽然没有进行任何格式化,但是它类似于println()方法。

System.out.format() is same as System.out.format()System.out.printf() method.System.out.printf()方法相同。

String.format()和System.out.printf()之间的区别 (Difference between String.format() and System.out.printf())

  1. String.format() returns a formatted string. System.out.printf() also prints a formatted string to the console.String.format()返回格式化的字符串。 System.out.printf()也将格式化的字符串打印到控制台。
  2. printf() uses the java.util.Formatter class to parse the format string and generate the output.printf()使用java.util.Formatter类解析格式字符串并生成输出。

格式说明符 (Format Specifiers)

Let’s look at the available format specifiers available for printf:

让我们看一下可用于printf的可用格式说明符:

  • %c character%c个字符
  • %d decimal (integer) number (base 10)%d个十进制(整数)数字(以10为底)
  • %e exponential floating-point number%e指数浮点数
  • %f floating-point number%f个浮点数
  • %i integer (base 10)%i整数(以10为底)
  • %o octal number (base 8)%o八进制数(以8为底)
  • %s String%s字串
  • %u unsigned decimal (integer) number%u无符号十进制(整数)数字
  • %x number in hexadecimal (base 16)以十六进制表示的%x个数字(以16为基)
  • %t formats date/time%t格式化日期/时间
  • %% print a percent sign%%打印百分号
  • \% print a percent sign\%打印百分号

Note: %n or \n are used as line separators in printf().

注意%n\ n用作printf()行分隔符。

转义字符 (Escape Characters)

Following are the escape characters available in printf():

以下是printf()可用的转义字符:

  • \b backspace\ b退格键
  • \f next line first character starts to the right of current line last character\ f下一行第一个字符从当前行最后一个字符的右边开始
  • \n newline\ n换行符
  • \r carriage return\ r回车
  • \t tab\ t标签
  • \\ backslash\\反斜杠

格式说明符完整语法 (Format Specifiers Full Syntax)

Let’s look at the full syntax of format specifiers with the extended set:

让我们看一下带有扩展集的格式说明符的完整语法:

%<flags><width><.precision>specifier

flags can be set as + for right-aligning, and – for left-aligning.

可以将标志设置为+(用于右对齐)和–(用于左对齐)。

Next, fire up your Jshell and start using printf()!

接下来,启动您的Jshell并开始使用printf()

数字格式 (Number Formatting)

Here’s an example:

这是一个例子:

|  Welcome to JShell -- Version 12.0.1
|  For an introduction type: /help introjshell> int x = 10
x ==> 10jshell> System.out.printf("Formatted output is: %d %d%n", x, -x)
Formatted output is: 10 -10

Let’s use some precision formatting:

让我们使用一些精确格式:

jshell> float y = 2.28f
y ==> 2.28jshell> System.out.printf("Precision formatting upto 4 decimal places %.4f\n",y)Precision formatting upto 4 decimal places 2.2800jshell> float z = 3.147293165f
z ==> 3.147293jshell> System.out.printf("Precision formatting upto 2 decimal places %.2f\n",z)Precision formatting upto 2 decimal places 3.15

As you can see it rounds off to the next decimal in the second case.

如您所见,在第二种情况下,它会四舍五入到下一个小数。

宽度说明符,对齐,用零填充 (Width Specifier, Aligning, Fill With Zeros)

In this section, we’ll see three examples for each of these:

在本节中,我们将为每个示例看到三个示例:

jshell> System.out.printf("'%5.2f'%n", 2.28);
' 2.28'

As you can see the width specifier allocates 5 characters width. The content is right aligned by default.

如您所见,宽度说明符分配5个字符的宽度。 默认情况下,内容右对齐。

Filling with zeros

用零填充

Empty spaces to the left of the first character can be filled with zeroes as shown below:

第一个字符左侧的空白可以用零填充,如下所示:

jshell> System.out.printf("'%05.2f'%n", 2.28);
'02.28'jshell> System.out.printf("'%010.2f'%n", 2.28);
'0000002.28'jshell> System.out.printf("'%010.2f'%n", -2.28);
'-000002.28'jshell> System.out.printf("'%010.2f'%n", 1234567.89);
'1234567.89'jshell> System.out.printf("'%010.2f'%n", -1234567.89);
'-1234567.89'

Aligning
By default, it is a + which means right aligned.

对齐
默认情况下,它是一个+,表示右对齐。

jshell> System.out.printf("'%10.2f'%n", 2.28);
'      2.28'

The following code, aligns to the left:

下面的代码向左对齐:

jshell> System.out.printf("'%-10.2f'%n", 2.28);
'2.28      '

Using Comma and Locale:

使用逗号和语言环境:

jshell> System.out.printf(Locale.US, "%,d %n", 5000);
5,000

字符串,布尔格式 (String, Boolean formatting)

Let’s look at String formatting with a few basic examples:

让我们看一下一些基本示例的字符串格式:

jshell> System.out.printf("%s %s!%n","Hello","World");
Hello World!
jshell> System.out.printf("%s\f%s!%n","Hello","World!");
HelloWorld!!
jshell> System.out.printf("%s\\%s!%n","Hello","World!");
Hello\World!!

Uppercase:

大写:

jshell> System.out.printf("%s %S!%n","Hello","World");
Hello WORLD!

Boolean formatting examples are given below:

布尔格式示例如下:

jshell> System.out.printf("%b%n", false);
falsejshell> System.out.printf("%b%n", 0.5);
truejshell> System.out.printf("%b%n", "false");
true

时间格式 (Time Formatting)

‘H’, ‘M’, ‘S’ – Hours, Minutes, Seconds
‘L’, ‘N’ – to represent the time in milliseconds and nanoseconds accordingly
‘p’ – AM/PM
‘z’ – prints out the difference from GMT.

'H', 'M', 'S' –小时,分钟,秒
'L', 'N' –分别表示毫秒和纳秒的时间
'p'上午/下午
'z'打印出与GMT的区别。

jshell> Date date = new Date();
date ==> Fri Apr 19 02:15:36 IST 2019jshell> System.out.printf("%tT%n", date);
02:15:36jshell> System.out.printf("H : %tH, M: %tM, S: %tS%n",date,date,date)
H : 02, M: 15, S: 36

The latter one requires many arguments which are the same.
Instead, we can replace them with a single one:

后者需要许多相同的论点。
相反,我们可以将它们替换为一个:

jshell> System.out.printf("%1$tH:%1$tM:%1$tS %1$Tp GMT %1$tz  %n", date)
02:15:36 AM GMT +0530

日期格式 (Date Formatting)

Date formatting has the following special characters

日期格式具有以下特殊字符

A/a – Full day/Abbreviated day
B/b – Full month/Abbreviated month
d – formats a two-digit day of the month
m – formats a two-digit month
Y – Full year/Last two digits of the Year
j – Day of the year

A / a –全天/缩写天
B / b –整月/缩写月
d –格式化一个两位数的日期
m –格式化两位数的月份
Y –全年/年份的最后两位数字
j –一年中的一天

jshell> System.out.printf("%s %tB %<te, %<tY", "Current date: ", date);
Current date:  April 19, 2019jshell> System.out.printf("%1$td.%1$tm.%1$ty %n", date);
19.04.19jshell> System.out.printf("%s %tb %<te, %<ty", "Current date: ", date);
Current date:  Apr 19, 19

结论 (Conclusion)

In this tutorial, we discussed the various types of formatting possible using printf() method.

在本教程中,我们讨论了使用printf()方法可能进行的各种格式化。

翻译自: https://www.journaldev.com/28692/java-printf-method

printf格式化字符串

printf格式化字符串_Java printf()–将格式化的字符串打印到控制台相关推荐

  1. java输入数字返回字符串_java Scanner输入数字、字符串

    package java05; import java.util.Scanner;//1.导包 /* Scanner类的功能,可以实现键盘输入数据,到程序当中 引用类型的一班使用步骤: 1.导包 2. ...

  2. java 时间格式化 星期_Java SimpleDateFormate时间格式化

    首页 > 基础教程 > 常用类 > 常用 Date类 Java SimpleDateFormate时间格式化 java中SimpleDateFormate是时间简单格式化类,它允许格 ...

  3. java 格式化日期_Java的日期格式化常用方法

    public class SimpleDateFormatextends DateFormat SimpleDateFormat 是一个以与语言环境有关的方式来格式化和解析日期的具体类.它允许进行格式 ...

  4. java 格式化位数_java数字如何格式化?

    展开全部 import java.text.DecimalFormat; public class Test{ public static void main(String[] args){ doub ...

  5. java转换为字符串_java – 如何从int转换为字符串?

    正常方式是Integer.toString(i)或String.valueOf(i). 串联将工作,但它是非常规的,可能是一个难闻的气味,因为它暗示作者不知道上述两种方法(他们不知道什么?). Jav ...

  6. java字符串怎么拼接字符串_Java中String使用+ 拼接字符串的原理是什么?

    来看一段代码 public class Test { String str1 = "51"; String str2 = "manong"; String st ...

  7. java 根据特殊字符截取字符串_java中如何截取特殊字符串

    展开全部 给你推荐java 字符e69da5e6ba903231313335323631343130323136353331333365653739串截取的三种方法:split()+正则表达式来进行截 ...

  8. java 混淆字符串_Java逆向基础之ZKM字符串混淆与还原

    为了防止静态分析,ZMK在混淆时对输出的字符串使用对称加密方法进行加密 早期的ZKM只在静态代码块的时候进行简单的异或加密,后续版本使用了流加密技术进行二次加密 看一个简单的字符串输出例子packag ...

  9. Java json拼接字符串_Java中拼接json格式字符串

    如果需要表示的是name-value格式的, 在Java文件中的代码如下: @Override protected void doPost(HttpServletRequest req, HttpSe ...

最新文章

  1. C# Unity编程终极指南
  2. python 报错 Missing dependencies for SOCKS support 解决方法
  3. 运维角度浅谈MySQL数据库优化(转自:2018-03-10 李振良 JAVA高级架构)
  4. 访存优化_Hibernate事实:多级访存
  5. html如何实现字体逐个输入,HTML – 如何将字体真棒图标插入文本输入?
  6. 汉诺塔问题(递归思想)(堆栈学习)
  7. 超级素数幂--全国模拟(一)
  8. Iterator迭代器遍历Map集合
  9. python lmdb使用
  10. 青春-转自韩寒Sina Blog
  11. springboot项目报错-The Bean Validation API is on the classpath but no implementation could be found
  12. Win7显示器颜色不正常的原因及解决方法
  13. 免费PDF翻译,不限页数,不限字数,保留排版
  14. 我对IT项目经理工作的理解
  15. BMP图片加马赛克C语言C++超简单
  16. jquery easyui datagrid 列自适应窗口宽度
  17. 2021-05-11 MongoDB面试题 MongoDB是什么
  18. java中的double 类型数据相加问题
  19. mmap函数和munmap函数
  20. ThinkPHP 入门

热门文章

  1. 特殊的forward_list操作
  2. 【灵感】wifi通过wifi发送优惠信息
  3. vimnbsp;自动识别UTF8和GB2312
  4. 8.26~8.30-广州软件所-实习工作日记
  5. [转载] python下载安装教程
  6. [转载] Python中字符串的处理方法
  7. [转载] python的变量和C++的变量有什么区别
  8. Vue.js 学习笔记 八 v-for
  9. 数据加载中,请稍等......
  10. 抽象工厂模式 Abstract Factory Pattern