1

Consider a string which is needed to be inserted in some query or file where the length of string should be equal to 40. If length of string is less than 40, then it should append empty characters till length 40 is achieved, and then it needs to be inserted. How should I do this?

 void addstring(String str)
 {
      int len=str.length();
      PrintStream out=new PrintStream();
      if(len<=40)
      {
          out.print(str);
      }
      else
      {
          //make the string of length 40 by appending blank character and write to the file. 
      }
 }
aioobe
  • 383,660
  • 99
  • 774
  • 796
user3678383
  • 105
  • 10

4 Answers4

1

You can use printf as follows:

out.printf("%-40s", str);

For details on the format string, refer to Format String Syntax in the documentation of Formatter.

Note that if the string exceeds 40 characters, the string as a whole will be printed (without any padding spaces of course), so the if statement is redundant and can be dropped.

If you're using Guava you can use Strings.padEnd.

If you're using Apache Commons, you can use StringUtils.repeat and construct the padding manually.

aioobe
  • 383,660
  • 99
  • 774
  • 796
0

You can use StringUtils.repeat() method if you are using Apache commons.

String extraStr = StringUtils.repeat(" ", 40-len);

And then append it to your string.

Naman Gala
  • 4,480
  • 1
  • 18
  • 48
0

This technique is called 'padding', see here for more details.

Also, I would advise to check for a length greater than or equal to 40:

if (len >= 40)
{
    out.print(str);
}
else
{
    out.printf("%-40s", str);
}
Community
  • 1
  • 1
Glorfindel
  • 19,729
  • 13
  • 67
  • 91
0

Use the following:

if(str.length()<40) {
    out.printf("%-40s", str);
} else {
    out.printf("larger in size");
}
Vitalii Elenhaupt
  • 6,666
  • 3
  • 23
  • 39