String.format()函数的简单用法

目录

1.String.format()函数的用法

2.常用转换符

3.常用标识


1.String.format()函数的用法

String.format()函数类似于printf()函数,能够对字符串进行格式化或是进行加工,printf()函数直接将结果打印出来,而String.format()函数能够返回格式化后的字符串。

例如

public class Demo {
    public static void main(String[] args) {
        int sum = 200;
        String s = String.format("sum = %d", 10);
        System.out.println(s);
    }
}

运行结果

2.常用转换符

转换符 说明 示例
%c 字符类型 ‘a’
%s 字符串类型 “hello”
%b 布尔类型 true
%d 整数类型(十进制) 10
%f 浮点型 3.14
%x(X) 整数类型(十六进制) a(A)(十进制下为10)
%o 整数类型(八进制) 12(十进制下为10)
%% 百分比类型 %%(%是特殊字符,%%才会显示%)
%e 指数类型 1.2e+5

示例

public class Demo {
    public static void main(String[] args) {
        String s1 = String.format("%c %s %b %d",'a', "abc", true, 20);
        System.out.println(s1);
        String s2 = String.format("%f,%x,%o,%%,%e",3.1,10,10,3.1e+4);
        System.out.println(s2);
    }
}

运行结果

  


3.常用标识

标识 说明 示例
+ 使正数表示出正号 ("%+d", 12)
- 左对齐,不够的位数补空格(不加负号时为右对齐)

("%-5d", 12)

("%5d", 12)

0 数字前面补0 ("%05d", 12)
空格 在位数不够的地方补空格 ("% 5d", 12)
# 如果为十六进制数字,则加上ox;八进制数字,则加上o;浮点数则包含小数点

("%#x",12)

("%#o", 12)

, 以,对数字进行分组,三位一组(常用于显示金额) ("%,f",122222.22)

示例

public class Demo {
    public static void main(String[] args) {
        String s1 = String.format("%+d,%-5d,%5d,%05d,% 5d", 12, 12, 12, 12 ,12, 12);
        System.out.println(s1);
        String s2 = String.format("%#x %#o %,f",12,12,122222.22);
        System.out.println(s2);
    }
}

运行结果

 

猜你喜欢

转载自blog.csdn.net/2301_76161469/article/details/131388047