Take the 2-minute tour ×

Possible Duplicate:
How can I pad a String in Java?

I have a stuation in which my method1() return the string of various size and I want to display the string in a fix space (say length 50 character) I can use String.substring() if the length is greater than 50 character but not sure what to do if the string length is less than 50 character , how can I achieve that ?

for example my method1() return (in different call) :

While method2() return :

and I want to print the result like

John                 First
Michael              Second
J                    Third
Ab                   Forth

I don't want to use any other character except space.

share|improve this question
What have you tried so far? –  Alex Feinman Oct 13 '11 at 16:34
I have tried String.format() but that did not help –  Ashish Tyagi Oct 13 '11 at 16:35
add comment

marked as duplicate by James Black, Kirk Woll, Adamski, Joe, Graviton Oct 14 '11 at 2:36


3 Answers

up vote 1 down vote accepted
public String toFixedLength(String str, int sz) {      
  String ret;
  int len = str.length();

  if (len == sz) {
    ret = str;
  } else if (len > sz) {
    ret = str.substring(0, sz);
  } else { // len < sz
    StringBuilder sb = new StringBuilder(str);

    char[] ch = new char[sz - len];
    Arrays.fill(ch, ' ');
    ret = sb.toString();

  return ret;
share|improve this answer
not working in the following scenario –  Ashish Tyagi Oct 13 '11 at 17:06
add comment

Just check the string's length() and add the required number of spaces (say, in a cycle)

share|improve this answer
add comment

If you have a string with a length of less than fifty characters and you want to pad it out, you could just do:

int temp = yourstring.length

for(int i = 0; i < (50-temp); i++){
  yourstring = yourstring + " ";

I'm pretty sure that'd work, if yourstring is the string you're trying to pad and you haven't used i as an integer previously in your code. This way you only have to use space.

share|improve this answer
add comment
