0

I'm deconstructing a Java object, taking all the required String values from the getters and concatenating all these into one String per object. I then i want to store each string is an

   ArrayList<String>

I'm concatenating the strings into one string per object so i can print it out in a pdf document (pdfbox) for a report... I want to format each row to be the identical as if in a table. E.g regardless if the String1 is 3 characters or 103 characters long it will always fill 25 characters space --either substring to make smaller or buffered with space to make larger depending on what's required.

My question is how to do this efficiently? For this example lets say I require that every entry is 25 characters long. So for each value I'm appending below how do i enforce that all entries are 25 chars long?

    String SPACE="    ";
    for(People peeps: list){
        builder = new StringBuilder();
        name =(peeps.getName());
        // if(name.length()>25){name=name.substring(0,25);}
        builder.append(name)                
           .append(SPACE)
           .append(peeps.getCode())
           .append(SPACE)
           .append(peeps.getReference())
           .append(SPACE)
           .append(peeps.getDate())
           .append(SPACE)
           .append(peeps.getStatus())
           .append(SPACE)
           .append(peeps.getValue());

       reportList.add(builder.toString());
    }

e.g

Dmitriy Khaykin
  • 5,238
  • 1
  • 20
  • 32
user1843591
  • 1,074
  • 3
  • 17
  • 37

2 Answers2

2

Use the Formatter class.

StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb);
sb.append("|");
formatter.format("%-25.25s", "This is some text with more than 25 characters.");
sb.append("|");
formatter.format("%-25.25s", "Some text with less.");
sb.append("|");
formatter.format("%-25.25s", "Some other text.");
sb.append("|");
System.out.println(formatter.toString());

Output:

|This is some text with mo|Some text with less.     |Some other text.         |
Sebastian Höffner
  • 1,864
  • 2
  • 26
  • 37
1

Apache Commons provides easy to use API to work with Strings:

name = StringUtils.substring(name, 0, 25);
name = StringUtils.leftPad(name, 25, ' ');
hoaz
  • 9,883
  • 4
  • 42
  • 53