字符串格式化String.format

参考网址:https://blog.csdn.net/rlk512974883/article/details/80829985

说明:

String类的format()方法用于创建格式化的字符串以及连接多个字符串对象

format(String format, Object... args) 新字符串使用本地语言环境,制定字符串格式和参数生成格式化的新字符串。

format(Locale locale, String format, Object... args) 使用指定的语言环境,制定字符串格式和参数生成格式化的字符串。

例如:

对字符、字符串进行格式化 

占位符格式为: %[index$][标识][最小宽度]转换符 

可用标识:

   -,在最小宽度内左对齐,右边用空格补上。

可用转换符:

   s,字符串类型。

   c,字符类型,实参必须为char或int、short等可转换为char类型的数据类型,否则抛IllegalFormatConversionException异常。

   b,布尔类型,只要实参为非false的布尔类型,均格式化为字符串true,否则为字符串false。

   n,平台独立的换行符(与通过 System.getProperty("line.separator") 是一样的)

示例——将"hello"格式化为"  hello"----(前加空格)
String raw = "hello";
String str = String.format("%1$7s", raw);
// 简化
//String str = String.format("%7s", raw);

示例——将"hello"格式化为"hello  "----(后加空格)
String raw = "hello";
String str = String.format("%1$-7s", raw);
// 简化
//String str = String.format("%-7s", raw);

String number = str.replaceAll("\\s","0");-----替换
System.out.println("res:::"+number);//00hello
System.out.println("res:::"+number);//hello00
发布了19 篇原创文章 · 获赞 15 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/aidou1314/article/details/90258916