java - 生成固定长度的字符串,用空格填充
我需要生成固定长度的字符串来生成基于字符位置的文件。 缺少的字符必须填充空格字符。
例如,字段CITY具有15个字符的固定长度。 输入“芝加哥”和“里约热内卢”的输出是" Chicago"
" Rio de Janeiro"。
11个解决方案
101 votes
从Java 1.5开始,我们可以使用方法java.lang.String.format(String,Object ...)并使用类似printf的格式。
格式字符串"%1$15s"完成这项工作。 其中1$表示参数索引,s表示参数是String,15表示String的最小宽度。全部放在一起:"%1$15s"。
对于一般方法,我们有:
public static String fixedLengthString(String string, int length) {
return String.format("%1$"+length+ "s", string);
}
也许有人可以建议另一个格式字符串用特定字符填充空白区域?
Rafael Borja answered 2019-06-01T01:06:10Z
44 votes
利用00New York的空格填充,并用所需的字符替换它们。
String toPad = "Apple";
String padded = String.format("%8s", toPad).replace(' ', '0');
System.out.println(padded);
印刷品00New York。
更新更高性能的版本(因为它不依赖于00New York),这对空格没有任何问题(对于Rafael Borja而言是提示)。
int width = 10;
char fill = '0';
String toPad = "New York";
String padded = new String(new char[width - toPad.length()]).replace('\0', fill) + toPad;
System.out.println(padded);
印刷品00New York。
但是需要添加一个检查以防止尝试创建负长度的char数组。
mike answered 2019-06-01T01:06:57Z
17 votes
此代码将具有给定数量的字符; 填充空格或在右侧截断:
private String leftpad(String text, int length) {
return String.format("%" + length + "." + length + "s", text);
}
private String rightpad(String text, int length) {
return String.format("%-" + length + "." + length + "s", text);
}
Kurt Huwig answered 2019-06-01T01:07:22Z
10 votes
你也可以写一个简单的方法,如下所示
public static String padString(String str, int leng) {
for (int i = str.length(); i <= leng; i++)
str += " ";
return str;
}
Yashpal Singla answered 2019-06-01T01:07:47Z
9 votes
Guava库有Strings.padStart,它可以完全满足您的需求,还有许多其他有用的实用程序。
jricher answered 2019-06-01T01:08:12Z
8 votes
import org.apache.commons.lang3.StringUtils;
String stringToPad = "10";
int maxPadLength = 10;
String paddingCharacter = " ";
StringUtils.leftPad(stringToPad, maxPadLength, paddingCharacter)
比Guava imo更好的方式。 从未见过使用Guava但Apache String Utils的单个企业Java项目非常常见。
anon58192932 answered 2019-06-01T01:08:38Z
8 votes
对于右侧垫,您需要String.format("%0$-15s", str) - 标志将做右垫非 - 将做左垫
看看我的例子
[http://pastebin.com/w6Z5QhnJ]
输入必须是字符串和数字
示例输入:Google 1
Bui Dinh Ngoc answered 2019-06-01T01:09:30Z
4 votes
这是一个巧妙的伎俩:
// E.g pad("sss","00000000"); should deliver "00000sss".
public static String pad(String string, String pad) {
/*
* Add the pad to the left of string then take as many characters from the right
* that is the same length as the pad.
* This would normally mean starting my substring at
* pad.length() + string.length() - pad.length() but obviously the pad.length()'s
* cancel.
*
* 00000000sss
* ^ ----- Cut before this character - pos = 8 + 3 - 8 = 3
*/
return (pad + string).substring(string.length());
}
public static void main(String[] args) throws InterruptedException {
try {
System.out.println("Pad 'Hello' with ' ' produces: '"+pad("Hello"," ")+"'");
// Prints: Pad 'Hello' with ' ' produces: ' Hello'
} catch (Exception e) {
e.printStackTrace();
}
}
OldCurmudgeon answered 2019-06-01T01:09:55Z
2 votes
以下是包含测试用例的代码;):
@Test
public void testNullStringShouldReturnStringWithSpaces() throws Exception {
String fixedString = writeAtFixedLength(null, 5);
assertEquals(fixedString, " ");
}
@Test
public void testEmptyStringReturnStringWithSpaces() throws Exception {
String fixedString = writeAtFixedLength("", 5);
assertEquals(fixedString, " ");
}
@Test
public void testShortString_ReturnSameStringPlusSpaces() throws Exception {
String fixedString = writeAtFixedLength("aa", 5);
assertEquals(fixedString, "aa ");
}
@Test
public void testLongStringShouldBeCut() throws Exception {
String fixedString = writeAtFixedLength("aaaaaaaaaa", 5);
assertEquals(fixedString, "aaaaa");
}
private String writeAtFixedLength(String pString, int lenght) {
if (pString != null && !pString.isEmpty()){
return getStringAtFixedLength(pString, lenght);
}else{
return completeWithWhiteSpaces("", lenght);
}
}
private String getStringAtFixedLength(String pString, int lenght) {
if(lenght < pString.length()){
return pString.substring(0, lenght);
}else{
return completeWithWhiteSpaces(pString, lenght - pString.length());
}
}
private String completeWithWhiteSpaces(String pString, int lenght) {
for (int i=0; i
pString += " ";
return pString;
}
我喜欢TDD;)
Palgaz answered 2019-06-01T01:10:27Z
0 votes
public static String padString(String word, int length) {
String newWord = word;
for(int count = word.length(); count < length; count++) {
newWord = " " + newWord;
}
return newWord;
}
hack4greatness answered 2019-06-01T01:10:45Z
0 votes
这段代码效果很好。
String ItemNameSpacing = new String(new char[10 - masterPojos.get(i).getName().length()]).replace('\0', ' ');
printData += masterPojos.get(i).getName()+ "" + ItemNameSpacing + ": " + masterPojos.get(i).getItemQty() +" "+ masterPojos.get(i).getItemMeasure() + "\n";
快乐编码!!
sudharsan chandrasekaran answered 2019-06-01T01:11:12Z