Generate fixed length Strings filled with whitespaces

后端 未结 13 969
借酒劲吻你
借酒劲吻你 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条回答
  •  -上瘾入骨i
    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

    I like TDD ;)

提交回复
热议问题