Java: String formatting with placeholders

为君一笑 提交于 2019-11-28 05:50:18

The MessageFormat class looks like what you're after.

System.out.println(MessageFormat.format("{0} + {1} = {2}", x, y, x + y));
Daniel Kaplan

Java has a String.format method that works similarly to this. Here's an example of how to use it. This is the documentation reference that explains what all those % options can be.

And here's an inlined example:

package com.sandbox;

public class Sandbox {

    public static void main(String[] args) {
        System.out.println(String.format("It is %d oclock", 5));
    }        
}

This prints "It is 5 oclock".

You can do this (using String.format):

int x = 4;
int y = 5;

String res = String.format("%d + %d = %d", x, y, x+y);
System.out.println(res); // prints "4 + 5 = 9"

res = String.format("%d %d", x, y);
System.out.println(res); // prints "4 5"

Slf4j has MessageFormatter.format() that accepts {} without the argument number, just like Python. Slf4j is a popular logging framework, but you don't have to use it for logging to use MessageFormatter.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!