实用程序类总是有一个固定长度的字符串?

时间:2014-12-10 08:39:25

标签: java string

根据我的要求,可能已经有某种apache或guava实用程序类了:

我想始终创建相同长度的字符串。丢失的字符应该用固定字符向左或向右填充。类似的东西:

Utils.filledString(teststring, " ", 5); //would ensure the teststring is always 5 chars long, and if not append whitespace to the right
Utils.filledString(teststring, "x", -5); //same as above, but fill the 5 chars left with an x

你明白了,可能它已经存在,但我找不到正确的关键字来找到它。

2 个答案:

答案 0 :(得分:5)

番石榴项目已有解决方案。 Google Guava String。 它被称为padEnd / padStart

答案 1 :(得分:2)

查看apache commons lang StringUtils:

StringUtils.rightPad(String str, int size, String padStr)
StringUtils.leftPad(String str, int size, String padStr

StringUtils.rightPad("bat", 5, "")    = "bat  "
StringUtils.leftPad("bat", 5, "x")    = "xxbat"