Problem · String
Implement Printf
Learn this problemProblem statement
Implement a small formatted-text function. For this exercise, assume the format pattern supports exactly %s, %d, and %%.
- Copy each ordinary character in
patternunchanged. %sconsumes the next string invaluesand inserts it verbatim.%dconsumes the next string, which represents a signed 32-bit decimal integer. Insert its canonical decimal representation: omit a leading plus sign and redundant leading zeroes, and write zero as0.%%inserts one literal percent sign and consumes no value.- Process only the original pattern. Percent signs inside an inserted value are ordinary output characters and are never interpreted again.
Return the resulting string. Every pattern is valid, every percent sign begins one of the three supported two-character directives, and the number of consuming directives equals values.length. Width, precision, and other directives are outside this exercise.
Function
formatPrintf(pattern: String, values: String[]) → StringExamples
Example 1
pattern = "%s scored %d%%"values = ["Ada","+007"]return = "Ada scored 7%"The two consuming directives insert Ada and normalized integer 7. The final escape inserts a percent sign.
Example 2
pattern = "[%s] %d"values = ["%d%%","-0000"]return = "[%d%%] 0"The inserted percent signs remain literal, while negative zero becomes 0.
Example 3
pattern = "%%%%"values = []return = "%%"Two percent escapes produce two literal percent signs without consuming any values.
Constraints
0 <= pattern.length <= 10^5.0 <= values.length <= 10^5.- All strings contain only printable ASCII characters; an argument used by
%smay be empty. - An argument used by
%dcontains an optional+or-followed by between1and10decimal digits, and its value lies from-2147483648through2147483647. - The total number of characters across all values is at most
10^5, and the returned string has at most2 * 10^5characters.