生成用空格填充的固定长度字符串

我需要生成一个固定长度的字符串来生成一个基于字符位置的文件。缺少的字符必须用空格字符填充。

As an example, the field CITY has a fixed length of 15 characters. For the inputs "Chicago" and "Rio de Janeiro" the outputs are

"        Chicago"
" Rio de Janeiro"
.

261267 次浏览

从 Java 1.5开始,我们可以使用方法 String.format (String,Object...)和类似 printf 的格式。

格式化字符串 "%1$15s"完成这项工作。在 1$表示参数索引的地方,s表示参数是 String,而 15表示 String 的最小宽度。 Putting it all together: "%1$15s".

对于一般方法,我们有:

public static String fixedLengthString(String string, int length) {
return String.format("%1$"+length+ "s", string);
}

Maybe someone can suggest another format string to fill the empty spaces with an specific character?

这里有一个小窍门:

// 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();
}
}

番石榴图书馆Strings.padStart,它可以完全满足您的需要,还有许多其他有用的实用程序。

您还可以编写如下所示的简单方法

public static String padString(String str, int leng) {
for (int i = str.length(); i <= leng; i++)
str += " ";
return str;
}

Here is the code with tests cases ;) :

@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<lenght; i++)
pString += " ";
return pString;
}

我喜欢 TDD;)

利用 String.format的空格填充,并用所需的字符替换它们。

String toPad = "Apple";
String padded = String.format("%8s", toPad).replace(' ', '0');
System.out.println(padded);

指纹 000Apple


更新 更高性能的版本(因为它不依赖于 String.format) ,这对空格没有问题(这里给出了 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

但是需要添加一个检查,以防止尝试创建长度为负的字符数组。

import org.apache.commons.lang3.StringUtils;


String stringToPad = "10";
int maxPadLength = 10;
String paddingCharacter = " ";


StringUtils.leftPad(stringToPad, maxPadLength, paddingCharacter)

比番石榴好多了。从未见过一个企业级 Java 项目使用 Guava,但是 ApacheStringUtils 非常常见。

对于右垫你需要 String.format("%0$-15s", str)

-标志将“右”垫,没有 -标志将“左”垫

看看我的例子:

import java.util.Scanner;
 

public class Solution {
 

public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("================================");
for(int i=0;i<3;i++)
{
String s1=sc.nextLine();
                

                

Scanner line = new Scanner( s1);
line=line.useDelimiter(" ");
               

String language = line.next();
int mark = line.nextInt();;
                

System.out.printf("%s%03d\n",String.format("%0$-15s", language),mark);
                

}
System.out.println("================================");
 

}
}

输入必须是一个字符串和一个数字

示例输入: Google 1

这段代码将具有给定数量的字符; 用空格填充或在右侧截断:

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);
}
public static String padString(String word, int length) {
String newWord = word;
for(int count = word.length(); count < length; count++) {
newWord = " " + newWord;
}
return newWord;
}

这个代码很好用。Expected output

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

Happy Coding!!

String.format("%15s",s) // pads left
String.format("%-15s",s) // pads right

很好的总结 给你

这个简单的函数对我很有用:

public static String leftPad(String string, int length, String pad) {
return pad.repeat(length - string.length()) + string;
}

祈求:

String s = leftPad(myString, 10, "0");
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
int s;
String s1 = sc.next();
int x = sc.nextInt();
System.out.printf("%-15s%03d\n", s1, x);
// %-15s -->pads right,%15s-->pads left
}
}
}

使用 printf()可以简单地格式化输出,而不使用任何库。

Apache 公共 lang3依赖项的 StringUtils 用于解决左/右填充

Lang3 提供了 StringUtils类,您可以在其中使用以下方法使用首选字符左填充。

StringUtils.leftPad(final String str, final int size, final char padChar);

这里,这是一个静态方法和参数

  1. str - string needs to be pad (can be null)
  2. size - the size to pad to
  3. padChar the character to pad with

We have additional methods in that StringUtils class as well.

  1. 右边
  2. 重复
  3. 不同的连接方法

我只是在这里添加了 Gradle 依赖关系,供您参考。

    implementation 'org.apache.commons:commons-lang3:3.12.0'

Https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.12.0

请参见此类的所有 utils 方法。

Https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/stringutils.html

GUAVA Library Dependency

这是来自 Jrich 的回答。Guava 库具有 Strings.padStart,它可以完全满足您的需要,还有许多其他有用的实用程序。