134

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

"        Chicago"
" Rio de Janeiro"
.

0

15 Answers 15

158

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

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

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?

8
  • 3
    Maybe someone can suggest another format string to fill the empty spaces with an specific character? - take a look a the answer I gave.
    – mike
    Commented Mar 28, 2015 at 10:42
  • 5
    According to docs.oracle.com/javase/tutorial/essential/io/formatting.html, 1$ represents the argument index and 15 the width Commented Apr 14, 2016 at 17:53
  • 3
    This will not limit the string to length 15. If it is longer, produced output will also be longer than 15
    – misterti
    Commented Jun 27, 2016 at 11:48
  • 1
    @misterti a string.substring would limit it to 15 characters. Best regards Commented Jun 28, 2016 at 12:30
  • 2
    I should have mentioned that, yes. But the point of my comment was to warn about the possibility of longer output than desired, which could be a problem for fixed length fields
    – misterti
    Commented Jun 28, 2016 at 16:40
69

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.


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).

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.

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

1
  • Updated code will works great. That what i expected @thanks mike Commented Oct 9, 2017 at 7:34
37

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);
}
0
26
String.format("%15s",s) // pads left
String.format("%-15s",s) // pads right

Great summary here Try here instead.. Link now dead 2

2
  • 3
    Flipped. String.format("%-15s",s) // pads right. s="HAMBURGER" gives you "HAMBURGERbbbbbb", where "b" = space. The content at the link shows the example, String s1 = String.format("{%20s}", "Hello Format"); and claims output is { Hello Format}, which I agree with. That's a pad left. Commented Dec 16, 2021 at 16:51
  • 1
    @SoftwareProphets Fixed. Thanks.
    – JGFMK
    Commented Jan 17, 2022 at 17:31
20

For right pad you need String.format("%0$-15s", str)

i.e. - sign will "right" pad and no - sign will "left" pad

See my example:

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

The input must be a string and a number

example input : Google 1

0
13
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.

12

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;
    }
2
  • 11
    This is definitely not the most performant answer. Since strings are immutable in Java you're essentially generating N new strings in memory with length equal to str.length+1 and thus is hugely wasteful. A much better solution would only perform one string concatenation regardless of input string length and utilize StringBuilder or some other more efficient way of string conatenation in the for loop. Commented Jun 27, 2017 at 17:34
  • 1
    @anon58192932 This does not seem to be the case since Java 9, openjdk.java.net/jeps/280, dzone.com/articles/… .
    – patrik
    Commented Dec 9, 2020 at 12:03
11

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

7

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

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

4

Apache common lang3 dependency's StringUtils exists to solve Left/Right Padding

Apache.common.lang3 provides the StringUtils class where you can use the following method to left padding with your preferred character.

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

Here, This is a static method and the parameters

  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. rightPad
  2. repeat
  3. different join methods

I just add the Gradle dependency here for your reference.

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

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

Please see all the utils methods of this class.

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html

GUAVA Library Dependency

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

1

This code works great. 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!!

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

This simple function works for me:

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

Invocation:

String s = leftPad(myString, 10, "0");
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
        }
    }
}

Use printf() to simply format output without using any library.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.