Generate fixed length Strings filled with whitespaces

JavaStringFormatting

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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?

Solution 2 - Java

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.

Solution 3 - Java

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

Solution 4 - Java

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

Solution 5 - Java

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

Great summary here

Solution 6 - Java

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.

Solution 7 - Java

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

Solution 8 - Java

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

Solution 9 - Java

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

Solution 10 - Java

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

Solution 11 - Java

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.

Solution 12 - Java

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

Solution 13 - Java

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

Solution 14 - Java

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

Solution 15 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRafael BorjaView Question on Stackoverflow
Solution 1 - JavaRafael BorjaView Answer on Stackoverflow
Solution 2 - JavamikeView Answer on Stackoverflow
Solution 3 - JavaKurt HuwigView Answer on Stackoverflow
Solution 4 - JavaBui Dinh NgocView Answer on Stackoverflow
Solution 5 - JavaJGFMKView Answer on Stackoverflow
Solution 6 - JavafIwJlxSzApHEZIlView Answer on Stackoverflow
Solution 7 - JavaYashpal SinglaView Answer on Stackoverflow
Solution 8 - JavajricherView Answer on Stackoverflow
Solution 9 - JavaOldCurmudgeonView Answer on Stackoverflow
Solution 10 - JavaPalgazView Answer on Stackoverflow
Solution 11 - JavaRCvaramView Answer on Stackoverflow
Solution 12 - Javasudharsan chandrasekaranView Answer on Stackoverflow
Solution 13 - Javahack4greatnessView Answer on Stackoverflow
Solution 14 - JavaWvdHoovenView Answer on Stackoverflow
Solution 15 - Javaarvindsis11View Answer on Stackoverflow