Question

Is it possible to create in java something like this someFunction("%s, %s, %s", 1, true, "qwe"); where result should be 1 true qwe?

I tried it with different approaches such as using PrintStream and some other classes but I can't figure out how to do it.

So far one things that seem certain is the definition:

public static String prepare(String format, Object... arguments) {
    return ???
}

But I cannot figure out how to do it past that. Can you give me some advices?

Was it helpful?

Solution 4

That's what String.format() is meant for

String.format("%s, %s, %s", 1, true, "666");

In your case,

return String.format(format, arguments);

OTHER TIPS

You can use String.format method:

public static String prepare(String format, Object... arguments) {
    // do same sanity checks if needed
    return String.format(format, arguments);
}

This is what String.format does, but I assume that you know that already, and would like to build your own function.

The header of the function that you have is correct. Now you need to make a counter count initially set to zero, create a StringBuilder, and run a loop that scans the format string.

When your loop encounters a character other than the '%', append that character to the StringBuilder. Otherwise, check the next character for a format that your program recognizes, and grab the object at the position count from the arguments array. Format the object as required, and append the result to StringBuilder; increment count.

Once the loop is over, StringBuilder contains the result string that you return to the callers.

Of course this is only a skeleton of the algorithm. A real implementation needs to take care of many other important things, such as

  • Checking that the count in the loop does not advance past the end of the arguments array
  • Checking that the final count is not less than the number of objects in the arguments
  • Checking that the format specifier can be applied to the object from the arguments array

and so on.

Yes, this is exactly what String.format() does:

public class Test {

  public static void main(String[] args) {  
    System.out.println(format("%s %s %s", 12, "A", true));
  }

  public static String format(String format, Object ... args) {
    return String.format(format, args);
  }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top