如何调整尾随空格?

时间:2011-09-21 21:17:17

标签: java

我正在写入java中的文件,但是输入到文件中的字符串是不同的,我如何根据字符串的长度调整尾随空格。

例如

First Name     Last Name     Address
----------     ---------     -------
Michael        Jordan        23 E. Jump Street
Larry          Bird          33 North Celtics Run

3 个答案:

答案 0 :(得分:8)

您可以使用String.format()

System.out.println(String.format("[%-20s]", "foo"));

会给你:

[foo                 ]

答案 1 :(得分:4)

如果您尝试使用填充写入文件,请考虑使用PrintWriter写入文件,并使用其printf(...)方法。 API将告诉您如何使用它。

如,

public class PrintfExample {
   public static void main(String[] args) {
      String formatString = "%-14s %-14s %-14s%n";
      String[][] data = {{"First Name", "Last Name", "Address"},
            {"---------", "---------", "---------"},
            {"Smith", "John", "100 Main St"}, 
            {"Michael", "Jordan", "23 E. Jump Street"},
            {"Larry", "Bird", "33 North Celtics Run"}};

      for (int i = 0; i < data.length; i++) {
         // you would be writing to a File wrapped in a PrintWriter using printf
         // instead of to System.out (which is in fact a PrintWriter object),
         // but the technique is the same.
         System.out.printf(formatString, data[i][0], data[i][1], data[i][2]);
      }
   }
}

答案 2 :(得分:1)

或者像这样,只需使用substring():

public class FormatFields {

private static final String [] [] data = {
        {"First Name", "Last Name", "Address"},
        {"----------", "---------", "-------"},
        {"Michael", "Jordan", "23 E. Jump Street"},
        {"Larry", "Bird", "33 North Celtics Run"}
};


private static final int FIELD_LENGTH = 20;
private static final String PADDING = "                    "; // 20 spaces

/**
 * @param args
 */
public static void main(String[] args) {

    for (int i = 0; i < data.length; i++) {
        for (int j = 0; j < data[i].length; j++) {

            System.out.print((data[i][j] + PADDING).substring(0, FIELD_LENGTH));

        }
        System.out.println();
    }
}

}

会给你

First Name          Last Name           Address             
----------          ---------           -------             
Michael             Jordan              23 E. Jump Street   
Larry               Bird                33 North Celtics Run