开发者

Way to format strings with "?" parameters to full string in java?

开发者 https://www.devze.com 2023-04-01 18:33 出处:网络
For example I want to implement class with method public 开发者_运维问答class Logger { public void info(String message, String[] params) {

For example I want to implement class with method

public 开发者_运维问答class Logger {

    public void info(String message, String[] params) {
    }
}

If input is

new Logger().info("Info: param1 is ? , param2 is ?", new  String[] {"a", "b"});

Output must be

Info: param1 is a , param2 is b

What is the easiest way to implement it?


You can use the String.format(String format, Object ... args) method for this. Instead of using a ?, you can do C style %x format, where x can be d (for int), s (for string), etc.

Example.

Also, you can view the Formatter.format class method. It shows you all formatting flags acceptale for formatting (String.format() method uses Formatter to do the formatting).


The following code does as you require.

public class Logger {

    public static void main(String[] args) {
        new Logger().info("Info: param1 is ?, param2 is ?", new String[] { "a", "b" });
        new Logger().info("Info: param1 is ?, param2 is ?", "a", "b");
    }

    public void info(final String message, final String... args) {
        System.out.printf(message.replace("?", "%s") + "%n", args);
    }

}

However, you should consider using correct formatting place-holders instead of '?'. For instance:

 public class Logger {

    public static void main(String[] args) {
        new Logger().info("Info: param1 is %s, param2 is %s", new String[] { "a", "b" });
        new Logger().info("Info: param1 is %s, param2 is %s", "a", "b");
    }

    public void info(final String message, final String... args) {
        System.out.printf(message + "%n", args);
    }

}

Both versions will print:

Info: param1 is a, param2 is b
Info: param1 is a, param2 is b


If you don't have to worry about escaping the '?', and you can't use printf() style format strings, you could get away with:

public void info(String message, String[] params) {
    System.out.println(
        String.format(message.replace("?", "%s"), params)
    );
}

Like so:

info("apple is to ? as eve is to ?",
    new String[] { "banana", "noon" });

Which prints: apple is to banana as eve is to noon


If you need more sophisticated logic, such as escaping, then you'll probably want a full-blown regexp Pattern-based search and replace.


in a loop on params[] use regexp to find every '?' in your string and substitute it with the current param. Beware of nulls and find a proper way to escape ? (guess \? will give some trouble, better ??)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号