【String】Java中字符串的占位符拼接

方式一

String.format()

static String str = "%s和%s的%s.一刻也不能%s,无论%s走到那里,都留下一首赞歌";

    public static void main(String[] args) {

        String format = String.format(str, "我", "我", "祖国", "分隔", "我","啦啦啦的马蒂");
        System.out.println(format);
        //输出结果:我和我的祖国.一刻也不能分隔,无论我走到那里,都留下一首赞歌

    }
View Code

方式二

MessageFormat.format()

import java.text.MessageFormat;

static String str = "{0}和{0}的{1}.一刻也不能{2},无论{0}走到那里,都留下一首赞歌";

    public static void main(String[] args) {

        String format = MessageFormat.format(str, "我", "祖国", "分隔", "啦啦啦啦的马蒂");
        System.out.println(format);
        //输出:我和我的祖国.一刻也不能分隔,无论我走到那里,都留下一首赞歌
    }
View Code

================================附录1:String.format()详解使用=============================================

参考地址:https://blog.csdn.net/anita9999/article/details/82346552

猜你喜欢

转载自www.cnblogs.com/sxdcgaq8080/p/12186200.html