简体   繁体   中英

Way to format strings with “?” parameters to full string in java?

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 ??)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM