Implement Basic Printf Formatter
Implement a basic version of printf in Java. Instead of printing to the console, the method must return the final formatted string.
The formatter supports three placeholders: %s for strings, %d for integers, and %f for floating point numbers. Placeholders must be replaced from left to right using the given argument values.
For %f, let x be the parsed floating point value. Compute rounded = round(x * 1,000,000) / 1,000,000, then print exactly 6 digits after the decimal point, padding trailing zeroes if needed. The decimal separator must be ..
Class
BasicPrintfFormatter
Method
Format
String format(String template, List<String> values)
- Returns the final formatted string after replacing all supported placeholders in
template.
%s is replaced by the next value exactly as given.
%d is replaced by the next value after parsing it as an integer.
%f is replaced by the next value after parsing it as a floating point number and formatting it with exactly 6 digits after the decimal point.
- Placeholders are matched and replaced from left to right.
- The input is valid: every placeholder is one of
%s, %d, or %f, and the number of placeholders equals the number of values.
Constraints
1 ≤ template.length() ≤ 100,000
0 ≤ values.size() ≤ 10,000
1 ≤ values[i].length() ≤ 100
template contains only printable ASCII characters.
- Every
%d value represents a valid signed integer in the range -1,000,000,000 to 1,000,000,000.
- Every
%f value represents a valid signed decimal number in the range -1,000,000,000.0 to 1,000,000,000.0.
- The result length will not exceed
1,000,000.
- No parameter value will be
null.
Examples
Example 1
format(template = "Hello %s, you have %d messages", values = List.of("Amit", "5"))
Output: "Hello Amit, you have 5 messages"
Explanation: %s is replaced by "Amit" and %d is replaced by integer 5.
Example 2
format(template = "Price: %f and item: %s", values = List.of("42.5", "book"))
Output: "Price: 42.500000 and item: book"
Explanation: %f is formatted with exactly 6 digits after the decimal point.
Example 3
format(template = "%s scored %d out of %d", values = List.of("Riya", "87", "100"))
Output: "Riya scored 87 out of 100"
Explanation: The placeholders are replaced in the same order as they appear in the template.