开发者

how to pad space within a string in java? [duplicate]

开发者 https://www.devze.com 2023-04-12 15:52 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: How can I pad a String in Java?
This question already has answers here: Closed 11 years ago.

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() ret开发者_开发问答urn (in different call) :
John
Michael
J
Ab

While method2() return :
first
Second
Third

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.


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, ' ');
    sb.append(ch);
    ret = sb.toString();
  }

  return ret;
}


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消