Generate fixed length Strings filled with whitespaces

后端 未结 13 934
借酒劲吻你
借酒劲吻你 2020-12-04 13:52

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 fi

相关标签:
13条回答
  • 2020-12-04 14:28

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

    0 讨论(0)
  • 2020-12-04 14:32

    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;
        }
    
    0 讨论(0)
  • 2020-12-04 14:35

    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.

    0 讨论(0)
  • 2020-12-04 14:38

    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?

    0 讨论(0)
  • 2020-12-04 14:39

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

    0 讨论(0)
  • 2020-12-04 14:39
    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)
提交回复
热议问题