记录对String.format(Formatter().format())方法的总结

简介: String.format其实是调用的Formatter.format: public static String format(String format, Object... args) { return new Formatter().format(format, args).toString(); } 第一个参数是格式化字符串,第二个参数是可变的被格式化的参数。

String.format其实是调用的Formatter.format:

    public static String format(String format, Object... args) {
        return new Formatter().format(format, args).toString();
    }

第一个参数是格式化字符串,第二个参数是可变的被格式化的参数。

我们主要看的是格式化参数的说明:

  • The format specifiers for general, character, and numeric types have the following syntax:
       %[argument_index$][flags][width][.precision]conversion

这个参数是用来格式化通用的、字符串、数字类型,主要说一下每个参数的作用:

% 用于表示这后面将是一个格式化数据的模板,
argument_index$ 表示要作用在第几个参数上,注意一定要加上'$',
flags 以下是flag的对照表,对不同的类型有不同的作用:
  • The following table summarizes the supported flags. y means the flag is supported for the indicated argument types.

    Flag General Character Integral Floating Point Date/Time Description
    '-' y y y y y The result will be left-justified.
    '#' y1 - y3 y - The result should use a conversion-dependent alternate form
    '+' - - y4 y - The result will always include a sign
    '  ' - - y4 y - The result will include a leading space for positive values
    '0' - - y y - The result will be zero-padded
    ',' - - y2 y5 - The result will include locale-specific grouping separators
    '(' - - y4 y5 - The result will enclose negative numbers in parentheses

    1 Depends on the definition of Formattable.

    2 For 'd' conversion only.

    3 For 'o', 'x', and 'X' conversions only.

    4 For 'd', 'o', 'x', and 'X' conversions applied to BigInteger or 'd' applied to byte, Byte, short, Short, int and Integer, long, and Long.

    5 For 'e', 'E', 'f', 'g', and'G' conversions only.

    Any characters not explicitly defined as flags are illegal and are reserved for future extensions. 

  • Width

    The width is the minimum number of characters to be written to the output. For the line separator conversion, width is not applicable; if it is provided, an exception will be thrown.

    Precision

    For general argument types, the precision is the maximum number of characters to be written to the output.

    For the floating-point conversions 'a', 'A', 'e','E', and 'f' the precision is the number of digits after the radix point. If the conversion is'g' or 'G', then the precision is the total number of digits in the resulting magnitude after rounding.

    For character, integral, and date/time argument types and the percent and line separator conversions, the precision is not applicable; if a precision is provided, an exception will be thrown.

    Argument Index

    The argument index is a decimal integer indicating the position of the argument in the argument list. The first argument is referenced by "1$", the second by "2$", etc.

    Another way to reference arguments by position is to use the '<' ('\u003c') flag, which causes the argument for the previous format specifier to be re-used. For example, the following two statements would produce identical strings:

       Calendar c = ...;
       String s1 = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c);
    
       String s2 = String.format("Duke's Birthday: %1$tm %<te,%<tY", c);
最重要的是conversion:
Conversion Argument Category Description
'b', 'B' general If the argument arg is null, then the result is "false". Ifarg is a boolean or Boolean, then the result is the string returned by String.valueOf(arg). Otherwise, the result is "true".
'h', 'H' general If the argument arg is null, then the result is "null". Otherwise, the result is obtained by invokingInteger.toHexString(arg.hashCode()).
's', 'S' general If the argument arg is null, then the result is "null". Ifarg implements Formattable, then arg.formatTo is invoked. Otherwise, the result is obtained by invokingarg.toString().
'c', 'C' character The result is a Unicode character
'd' integral The result is formatted as a decimal integer
'o' integral The result is formatted as an octal integer
'x', 'X' integral The result is formatted as a hexadecimal integer
'e', 'E' floating point The result is formatted as a decimal number in computerized scientific notation
'f' floating point The result is formatted as a decimal number
'g', 'G' floating point The result is formatted using computerized scientific notation or decimal format, depending on the precision and the value after rounding.
'a', 'A' floating point The result is formatted as a hexadecimal floating-point number with a significand and an exponent. This conversion isnot supported for the BigDecimal type despite the latter's being in thefloating point argument category.
't', 'T' date/time Prefix for date and time conversion characters. See Date/Time Conversions.
'%' percent The result is a literal '%' ('\u0025')
'n' line separator The result is the platform-specific line separator 

示例代码:

package main;

public class StringFormat {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		String format = "Haha.%1$(g%2$s%3$s";
		Object obj = 100f, object1 = "fdsafds", object2 = new StringFormat();
		String format2 = String.format(format, obj, object1, object2);
		System.out.println(format2);

		// String Format總結
		// %[argument_index$][flags][width][.precision]conversion 标准表达式

	}

}

运行结果:

Haha.100.000fdsafdsmain.StringFormat@6d6f6e28


目录
相关文章
|
6月前
for循环和String类下方法的一个练习题
for循环和String类下方法的一个练习题
66 1
|
4月前
|
Java
【编程基础知识】(讲解+示例实战)方法参数的传递机制(值传递及地址传递)以及String类的对象的不可变性
本文深入探讨了Java中方法参数的传递机制,包括值传递和引用传递的区别,以及String类对象的不可变性。通过详细讲解和示例代码,帮助读者理解参数传递的内部原理,并掌握在实际编程中正确处理参数传递的方法。关键词:Java, 方法参数传递, 值传递, 引用传递, String不可变性。
91 1
【编程基础知识】(讲解+示例实战)方法参数的传递机制(值传递及地址传递)以及String类的对象的不可变性
|
3月前
|
JavaScript 前端开发 开发者
|
6月前
|
JavaScript 算法 前端开发
JS算法必备之String常用操作方法
这篇文章详细介绍了JavaScript中字符串的基本操作,包括创建字符串、访问特定字符、字符串的拼接、位置查找、大小写转换、模式匹配、以及字符串的迭代和格式化等方法。
JS算法必备之String常用操作方法
|
5月前
|
JavaScript 前端开发 API
javaScript中常用的String方法以及注意点总结
本文总结了JavaScript中常用的String对象的方法及其注意事项,包括大小写转换、字符获取、子字符串截取、字符串拼接、去除空格、替换、分割以及查找字符串中字符的索引等操作。提供了每种方法的使用示例代码,帮助理解它们的具体用法和差异。
62 2
|
6月前
|
XML Java API
List与String相互转化方法汇总
本文汇总了List与String相互转化的多种方法,包括使用`String.join()`、`StringBuilder`、Java 8的Stream API、Apache Commons Lang3的`StringUtils.join()`以及Guava的`Joiner.on()`方法实现List转String;同时介绍了使用`split()`方法、正则表达式、Apache Commons Lang3的`StringUtils.split()`及Guava的`Splitter.on()`方法实现String转List。
232 1
List与String相互转化方法汇总
|
6月前
|
Java API 索引
【Java基础面试二十四】、String类有哪些方法?
这篇文章列举了Java中String类的常用方法,如`charAt()`、`substring()`、`split()`、`trim()`、`indexOf()`、`lastIndexOf()`、`startsWith()`、`endsWith()`、`toUpperCase()`、`toLowerCase()`、`replaceFirst()`和`replaceAll()`,并建议面试时展示对这些方法的熟悉度,同时深入理解部分方法的源码实现。
【Java基础面试二十四】、String类有哪些方法?
|
5月前
|
Java 索引
java基础扫盲-String类常用的方法
java基础扫盲-String类常用的方法
|
6月前
|
Java 索引
Java系列之 String indexOf() 方法
文章详细介绍了Java中`String`类的`indexOf()`方法的四种不同形式及其用法,包括查找字符和子字符串在字符串中的索引,并提供了相应的实例代码和输出结果。
|
6月前
|
Dragonfly Dart NoSQL
Dart ffi 使用问题之在Dart中调用String的toNativeUtf8方法时有什么是需要注意的
Dart ffi 使用问题之在Dart中调用String的toNativeUtf8方法时有什么是需要注意的