如何在 Java 中填充字符串? [英] How can I pad a String in Java?

查看:25
本文介绍了如何在 Java 中填充字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么简单的方法可以在 Java 中填充字符串吗?

Is there some easy way to pad Strings in Java?

似乎应该在一些类似 StringUtil 的 API 中,但我找不到任何可以做到这一点的东西.

Seems like something that should be in some StringUtil-like API, but I can't find anything that does this.

推荐答案

Apache StringUtils 有几种方法:leftPad, rightPad, centerrepeat.

Apache StringUtils has several methods: leftPad, rightPad, center and repeat.

但请注意——正如其他人在这个答案中提到和演示的那样——String.format() 和 JDK 中的 Formatter 类是更好的选择.在公共代码上使用它们.

But please note that — as others have mentioned and demonstrated in this answer — String.format() and the Formatter classes in the JDK are better options. Use them over the commons code.

这篇关于如何在 Java 中填充字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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