Java - truncate string from left with formatter flag

java, string-formatting

Solution

The `-` flag is for justification and doesn't seem to have anything to do with truncation.

The `.` is used for "precision", which apparently translates to truncation for string arguments.

I don't think format strings supports truncating from the left. You'll have to resort to

String.format("[%.5s]", s.length() > 5 ? s.substring(s.length()-5) : s);

Problem

I have a string, say: ``` String s = "0123456789"; ``` I want to pad it with a formatter. I can do this two ways: ``` String.format("[%1$15s]", s); //returns [ 0123456789] ``` or ``` String.format("[%1$-15s]", s); // returns [0123456789 ] ``` if I want to truncate text I do ``` String.format("[%1$.5s]", s); // returns [01234] ``` if I want to truncate from the left, I thought I could do this: ``` String.format("[%1$-.5s]", s); // throws MissingFormatWidthException ``` but this failed, so I tried this: ``` String.format("[%1$-0.5s]", s); // throws MissingFormatWidthException ``` as well as this: ``` String.format("[%1$.-5s]", s); // throws UnknownFormatConversionException ``` So how then do I truncate from the left using a format flag?

Original source