Java - truncate string from left with formatter flag

时光毁灭记忆、已成空白 提交于 2019-11-27 07:45:42

问题


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?


回答1:


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);



回答2:


I 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' - equals
'12345' - truncated

in addition:

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

output:

'  123' filled with 2 spaces before




回答3:


You could also use method for manipulating Strings

substring(startindex, endIndex)

Returns a string object that starts a the specified index an goes to, but doesn't include, the end index.

And also could try to use StringBuilder class.



来源:https://stackoverflow.com/questions/25630425/java-truncate-string-from-left-with-formatter-flag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!