Java - 使用格式化程序标志从左侧截断字符串 [英] Java - truncate string from left with formatter flag

查看:107
本文介绍了Java - 使用格式化程序标志从左侧截断字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,比如说:

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]

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

以及:

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

那么如何使用格式标志从左侧截断?

So how then do I truncate from the left using a format flag?

推荐答案

- 标志用于对齐,似乎没有任何内容做截断。

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

这篇关于Java - 使用格式化程序标志从左侧截断字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆