java拼接字符串、格式化字符串方式

1.代码

        //+
        String arg0 = "Bob";
        String arg1 = "Alice";
        System.out.println("hello," + arg0 + ". I am " + arg1 + ".");

        //StringBuilder.append
        StringBuilder builder = new StringBuilder();
        builder.append("hello,");
        builder.append(arg0);
        builder.append(". I am ");
        builder.append(arg1);
        builder.append(".");
        System.out.println(builder.toString());

        //String.format
        String formatStr = String.format("hello,%s. I am %s.", arg0, arg1);
        System.out.println(formatStr);

        //MessageFormat.format
        String formattedText = MessageFormat.format("hello,{0}. I am {1}.", arg0, arg1);
        System.out.println(formattedText);

2.运行结果

hello,Bob. I am Alice.
hello,Bob. I am Alice.
hello,Bob. I am Alice.
hello,Bob. I am Alice.

原文地址:https://www.cnblogs.com/hdwang/p/11084136.html