Java - crop line to left with formatting flag

I have a line, say:

String s = "0123456789"; 

I want to add it to the formatter. I can do this in two ways:

 String.format("[%1$15s]", s); //returns [ 0123456789] 

or

 String.format("[%1$-15s]", s); // returns [0123456789 ] 

if i want to crop the text i do

 String.format("[%1$.5s]", s); // returns [01234] 

If I want to truncate on 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 

and:

 String.format("[%1$.-5s]", s); // throws UnknownFormatConversionException 

So, how then do I crop to the left using the format flag?

+8
java string-formatting
source share
3 answers

The flag - for justification and seems to have nothing to do with truncation.

. used for "precision", which apparently means truncating the string arguments.

I don't think formatted strings support left truncation. You have to resort to

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

You can also use the method to manage strings.

 substring(startindex, endIndex) 

Returns a string object that starts the specified pointer, but goes, but does not include the end index.

You can also try using the StringBuilder class.

0
source share

Hope this is what you need:

 System.out.println("'" + String.format("%-5.5s", "") + "'"); System.out.println("'" + String.format("%-5.5s", "123") + "'"); System.out.println("'" + String.format("%-5.5s", "12345") + "'"); System.out.println("'" + String.format("%-5.5s", "1234567890.....") + "'"); 

output length is always 5:

'' - filled with 5 spaces
'123 , filled with 2 spaces after ' 12345 ' - equal to ' 12345 ' - truncated

additionally:

 System.out.println("'" + String.format("%5.5s", "123") + "'"); 

exit:

'123' , filled with two spaces before

0
source share

All Articles