生成带有空白的固定长度的字符串。

时间:2023-01-14 15:14:58

I need to produce fixed length string to generate a character position based file. The missing characters must be filled with space character.

我需要生成固定长度的字符串来生成一个基于字符的文件。缺失的字符必须填满空格字符。

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

例如,field CITY有固定长度的15个字符。对于输入“Chicago”和“里约热内卢de Janeiro”,输出是。

"        Chicago"
" Rio de Janeiro"
.

11 个解决方案

#1


92  

Since Java 1.5 we can use the method java.lang.String.format(String, Object...) and use printf like format.

从Java 1.5开始,我们可以使用Java .lang. string方法。格式(字符串,对象…)和使用printf格式。

The format string "%1$15s" do the job. Where 1$ indicates the argument index, s indicates that the argument is a String and 15 represents the minimal width of the String. Putting it all together: "%1$15s".

格式字符串"%1$15 "完成任务。其中1$表示参数索引,s表示参数为字符串,15表示字符串的最小宽度。把它放在一起:“%1$15s”。

For a general method we have:

对于一般方法,我们有:

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?

也许有人可以建议另一种格式字符串来填充特定字符的空白区域?

#2


38  

Utilize String.format's padding with spaces and replace them with the desired char.

利用字符串。格式的填充与空格,并替换它们与所需的字符。

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

Prints 000Apple.

打印000年苹果。


Update more performant version (since it does not rely on String.format), that has no problem with spaces (thx to Rafael Borja for the hint).

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

Prints 00New York.

打印00纽约。

But a check needs to be added to prevent the attempt of creating a char array with negative length.

但是需要添加一个检查,以防止创建带有负长度的char数组。

#3


11  

This code will have exactly the given amount of characters; filled with spaces or truncated on the right side:

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

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

#4


10  

You can also write a simple method like below

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

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

#5


8  

The Guava Library has Strings.padStart that does exactly what you want, along with many other useful utilities.

Guava图书馆有字符串。padStart和许多其他有用的实用工具一样,可以实现您想要的功能。

#6


6  

For right pad you need String.format("%0$-15s", str) - sign will do right pad non - will do left pad

对于右pad,您需要字符串。格式(“%0$-15s”,str) -符号将做右pad non -将做左pad。

see my example here

看看我的例子

http://pastebin.com/w6Z5QhnJ

http://pastebin.com/w6Z5QhnJ

input must be a string and a number

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

example input : Google 1

示例输入:谷歌1。

#7


5  

import org.apache.commons.lang3.StringUtils;

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

StringUtils.leftPad(stringToPad, maxPadLength, paddingCharacter)

Way better than Guava imo. Never seen a single enterprise Java project that uses Guava but Apache String Utils is incredibly common.

比番石榴还好。从未见过使用Guava的单个企业Java项目,但是Apache String Utils是非常常见的。

#8


2  

Here's a neat trick:

这里有一个窍门:

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

#9


2  

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

I like TDD ;)

我喜欢TDD,)

#10


0  

public static String padString(String word, int length) {
    String newWord = word;
    for(int count = word.length(); count < length; count++) {
        newWord = " " + newWord;
    }
    return newWord;
}

#11


0  

This code works great. 生成带有空白的固定长度的字符串。

这段代码伟大的工作。

  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!!

编码快乐! !

#1


92  

Since Java 1.5 we can use the method java.lang.String.format(String, Object...) and use printf like format.

从Java 1.5开始,我们可以使用Java .lang. string方法。格式(字符串,对象…)和使用printf格式。

The format string "%1$15s" do the job. Where 1$ indicates the argument index, s indicates that the argument is a String and 15 represents the minimal width of the String. Putting it all together: "%1$15s".

格式字符串"%1$15 "完成任务。其中1$表示参数索引,s表示参数为字符串,15表示字符串的最小宽度。把它放在一起:“%1$15s”。

For a general method we have:

对于一般方法,我们有:

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?

也许有人可以建议另一种格式字符串来填充特定字符的空白区域?

#2


38  

Utilize String.format's padding with spaces and replace them with the desired char.

利用字符串。格式的填充与空格,并替换它们与所需的字符。

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

Prints 000Apple.

打印000年苹果。


Update more performant version (since it does not rely on String.format), that has no problem with spaces (thx to Rafael Borja for the hint).

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

Prints 00New York.

打印00纽约。

But a check needs to be added to prevent the attempt of creating a char array with negative length.

但是需要添加一个检查,以防止创建带有负长度的char数组。

#3


11  

This code will have exactly the given amount of characters; filled with spaces or truncated on the right side:

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

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

#4


10  

You can also write a simple method like below

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

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

#5


8  

The Guava Library has Strings.padStart that does exactly what you want, along with many other useful utilities.

Guava图书馆有字符串。padStart和许多其他有用的实用工具一样,可以实现您想要的功能。

#6


6  

For right pad you need String.format("%0$-15s", str) - sign will do right pad non - will do left pad

对于右pad,您需要字符串。格式(“%0$-15s”,str) -符号将做右pad non -将做左pad。

see my example here

看看我的例子

http://pastebin.com/w6Z5QhnJ

http://pastebin.com/w6Z5QhnJ

input must be a string and a number

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

example input : Google 1

示例输入:谷歌1。

#7


5  

import org.apache.commons.lang3.StringUtils;

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

StringUtils.leftPad(stringToPad, maxPadLength, paddingCharacter)

Way better than Guava imo. Never seen a single enterprise Java project that uses Guava but Apache String Utils is incredibly common.

比番石榴还好。从未见过使用Guava的单个企业Java项目,但是Apache String Utils是非常常见的。

#8


2  

Here's a neat trick:

这里有一个窍门:

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

#9


2  

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

I like TDD ;)

我喜欢TDD,)

#10


0  

public static String padString(String word, int length) {
    String newWord = word;
    for(int count = word.length(); count < length; count++) {
        newWord = " " + newWord;
    }
    return newWord;
}

#11


0  

This code works great. 生成带有空白的固定长度的字符串。

这段代码伟大的工作。

  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!!

编码快乐! !