Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 792
qwazer Avatar asked Sep 02 '11 07:09

qwazer


People also ask

Can you format strings in Java?

In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string.

What is %s and %D in Java?

%d means number. %0nd means zero-padded number with a length. You build n by subtraction in your example. %s is a string. Your format string ends up being this: "%03d%s", 0, "Apple"

What is %s in string format?

The %s operator is put where the string is to be specified. The number of values you want to append to a string should be equivalent to the number specified in parentheses after the % operator at the end of the string value. The following Python code illustrates the way of performing string formatting.

How do I format string spacing in Java?

Use the String. format() method to pad the string with spaces on left and right, and then replace these spaces with the given character using String. replace() method.


1 Answers

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

like image 144
Buhake Sindi Avatar answered Sep 28 '22 05:09

Buhake Sindi