如何使用String.format使字符串居中?

时间:2011-11-16 15:41:40

标签: java string format string-formatting

public class Divers {
  public static void main(String args[]){

     String format = "|%1$-10s|%2$-10s|%3$-20s|\n";
     System.out.format(format, "FirstName", "Init.", "LastName");
     System.out.format(format, "Real", "", "Gagnon");
     System.out.format(format, "John", "D", "Doe");

     String ex[] = { "John", "F.", "Kennedy" };

     System.out.format(String.format(format, (Object[])ex));
  }
}

输出:

|FirstName |Init.     |LastName            |
|Real      |          |Gagnon              |
|John      |D         |Doe                 |
|John      |F.        |Kennedy             |

我希望输出居中。如果我不使用' - '标志,则输出将与右侧对齐。

我没有找到API中心文本的标记。

This文章提供了一些有关格式的信息,但没有任何关于中心的理由。

9 个答案:

答案 0 :(得分:19)

我很快就把它搞砸了。您现在可以在StringUtils.center(String s, int size)中使用String.format

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;

import org.junit.Test;

public class TestCenter {
    @Test
    public void centersString() {
        assertThat(StringUtils.center(null, 0), equalTo(null));
        assertThat(StringUtils.center("foo", 3), is("foo"));
        assertThat(StringUtils.center("foo", -1), is("foo"));
        assertThat(StringUtils.center("moon", 10), is("   moon   "));
        assertThat(StringUtils.center("phone", 14, '*'), is("****phone*****"));
        assertThat(StringUtils.center("India", 6, '-'), is("India-"));
        assertThat(StringUtils.center("Eclipse IDE", 21, '*'), is("*****Eclipse IDE*****"));
    }

    @Test
    public void worksWithFormat() {
        String format = "|%1$-10s|%2$-10s|%3$-20s|\n";
        assertThat(String.format(format, StringUtils.center("FirstName", 10), StringUtils.center("Init.", 10), StringUtils.center("LastName", 20)),
                is("|FirstName |  Init.   |      LastName      |\n"));
    }
}

class StringUtils {

    public static String center(String s, int size) {
        return center(s, size, ' ');
    }

    public static String center(String s, int size, char pad) {
        if (s == null || size <= s.length())
            return s;

        StringBuilder sb = new StringBuilder(size);
        for (int i = 0; i < (size - s.length()) / 2; i++) {
            sb.append(pad);
        }
        sb.append(s);
        while (sb.length() < size) {
            sb.append(pad);
        }
        return sb.toString();
    }
}

答案 1 :(得分:14)

public static String center(String text, int len){
    String out = String.format("%"+len+"s%s%"+len+"s", "",text,"");
    float mid = (out.length()/2);
    float start = mid - (len/2);
    float end = start + len; 
    return out.substring((int)start, (int)end);
}

public static void main(String[] args) throws Exception{
    // Test
    String s = "abcdefghijklmnopqrstuvwxyz";
    for (int i = 1; i < 200;i++){
        for (int j = 1; j < s.length();j++){
            center(s.substring(0, j),i);
        }
    }
}

答案 2 :(得分:7)

以下是使用apache commons lang StringUtils的答案。

请注意,您必须将jar文件添加到构建路径。如果你正在使用maven,请确保在依赖项中添加公共语言。

import org.apache.commons.lang.StringUtils;
public class Divers {
  public static void main(String args[]){

    String format = "|%1$-10s|%2$-10s|%3$-20s|\n";
    System.out.format(format, "FirstName", "Init.", "LastName");
    System.out.format(format,StringUtils.center("Real",10),StringUtils.center("",10),StringUtils.center("Gagnon",20);

    System.out.format(String.format(format, (Object[])ex));
  }
}

答案 3 :(得分:5)

https://www.leveluplunch.com/java/examples/center-justify-string/处的代码转换为方便的小型单行函数:

public static String centerString (int width, String s) {
    return String.format("%-" + width  + "s", String.format("%" + (s.length() + (width - s.length()) / 2) + "s", s));
}

用法:

public static void main(String[] args){
    String out = centerString(10, "afgb");
    System.out.println(out); //Prints "   afgb   "
}

我认为这是一个非常巧妙的解决方案,值得一提。

答案 4 :(得分:3)

从Java 9开始

“一个班轮”

    return n > s.length()
         ? " ".repeat((n - s.length()) / 2) + s + " ".repeat((n - s.length() + 1) / 2)
         : s;

其中:

  • " ".repeat(m)-填充空格。
  • n - s.length()-要填充的 diff 大小。
  • diff / 2-产生前缀大小(例如 5 / 2 = 2
  • (diff + 1) / 2-产生后缀大小(例如( 5 +1)/ 2 = 3

答案 5 :(得分:2)

我正在玩Mertuarez上面的优雅答案,并决定发布我的版本。

public class CenterString {

    public static String center(String text, int len){
        if (len <= text.length())
            return text.substring(0, len);
        int before = (len - text.length())/2;
        if (before == 0)
            return String.format("%-" + len + "s", text);
        int rest = len - before;
        return String.format("%" + before + "s%-" + rest + "s", "", text);  
    }

    // Test
    public static void main(String[] args) {
        String s = "abcde";
        for (int i = 1; i < 10; i++){
            int max = Math.min(i,  s.length());
            for (int j = 1; j <= max; j++){
                System.out.println(center(s.substring(0, j), i) + "|");
            }
        }
    }
}

输出:

a|
a |
ab|
 a |
ab |
abc|
 a  |
 ab |
abc |
abcd|
  a  |
 ab  |
 abc |
abcd |
abcde|
  a   |
  ab  |
 abc  |
 abcd |
abcde |
   a   |
  ab   |
  abc  |
 abcd  |
 abcde |
   a    |
   ab   |
  abc   |
  abcd  |
 abcde  |
    a    |
   ab    |
   abc   |
  abcd   |
  abcde  | 

与Mertuarez代码的实际差异:

  1. 我在前面做数学并在一次拍摄中制作最终的居中字符串,而不是制作太长的字符串然后从中获取子字符串。我认为这稍微高一点,但我没有测试它。
  2. 如果文字无法完美居中,我会一直把它放在左半边,而不是半个字符放在右半边。
  3. 如果文本的长度超过指定的长度,我将始终返回一个以原始文本开头为根的指定长度的子字符串。

答案 6 :(得分:1)

这是另一个例子。允许您选择在字符串的开头和结尾添加不同数量的填充字符时要如何处理中心。

使用Java 11 String::repeat

public class Strings {

    public enum Lean {
        START,
        END
    }

    public static String center(String value, int targetLength, Lean lean) {
        return center(value, targetLength, lean, ' ');
    }

    private static String center(String value, int targetLength, Lean lean, char pad) {

        if (targetLength < 1) {
            throw new IllegalArgumentException("Cannot center something into less than one space.");
        }

        int sourceLength = value.length();

        if (sourceLength == targetLength) {
            return value;
        }

        int paddingToAdd = targetLength - sourceLength;
        int half = paddingToAdd / 2;
        String spad = Character.toString(pad);
        String padding = spad.repeat(half);
        String startExtra = "";
        String endExtra = "";

        if (paddingToAdd % 2 == 1) {
            if (lean == Lean.START) {
                endExtra = spad;
            } else {
                startExtra = spad;
            }
        }

        return padding + startExtra + value + endExtra + padding;
    }
}



public class StringsTest {

    @Test
    public void centerAbcIn9LeanStart() {
        doTest(
                "abc",
                9,
                Strings.Lean.START,
                "   abc   "
        );
    }

    @Test
    public void centerAbcIn9LeanEnd() {
        doTest(
                "abc",
                9,
                Strings.Lean.END,
                "   abc   "
        );
    }

    @Test
    public void centerAbcIn10LeanStart() {
        doTest(
                "abc",
                10,
                Strings.Lean.START,
                "   abc    "
        );
    }

    @Test
    public void centerAbcIn10LeanEnd() {
        doTest(
                "abc",
                10,
                Strings.Lean.END,
                "    abc   "
        );
    }

    @Test
    public void centerAbcdIn9LeanStart() {
        doTest(
                "abcd",
                9,
                Strings.Lean.START,
                "  abcd   "
        );
    }

    @Test
    public void centerAbcdIn9LeanEnd() {
        doTest(
                "abcd",
                9,
                Strings.Lean.END,
                "   abcd  "
        );
    }

    @Test
    public void centerAbcdIn10LeanStart() {
        doTest(
                "abcd",
                10,
                Strings.Lean.START,
                "   abcd   "
        );
    }

    @Test
    public void centerAbcdIn10LeanEnd() {
        doTest(
                "abcd",
                10,
                Strings.Lean.START,
                "   abcd   "
        );
    }

    @Test
    public void centerAIn1LeanStart() {
        doTest(
                "a",
                1,
                Strings.Lean.START,
                "a"
        );
    }

    @Test
    public void centerAIn1LeanEnd() {
        doTest(
                "a",
                1,
                Strings.Lean.END,
                "a"
        );
    }

    @Test
    public void centerAIn2LeanStart() {
        doTest(
                "a",
                2,
                Strings.Lean.START,
                "a "
        );
    }

    @Test
    public void centerAIn2LeanEnd() {
        doTest(
                "a",
                2,
                Strings.Lean.END,
                " a"
        );
    }

    @Test
    public void centerAIn3LeanStart() {
        doTest(
                "a",
                3,
                Strings.Lean.START,
                " a "
        );
    }

    @Test
    public void centerAIn3LeanEnd() {
        doTest(
                "a",
                3,
                Strings.Lean.END,
                " a "
        );
    }

    @Test
    public void centerAbIn3LeanStart() {
        doTest(
                "ab",
                3,
                Strings.Lean.START,
                "ab "
        );
    }

    @Test
    public void centerAbIn3LeanEnd() {
        doTest(
                "ab",
                3,
                Strings.Lean.END,
                " ab"
        );
    }

    public void doTest(String value, int targetLength, Strings.Lean lean, String expected) {

        assertThat(
                "Test setup error: targetLength != expected.length()",
                targetLength,
                equalTo(expected.length()));

        assertThat(
                "Test setup error: value != expected.trim()",
                value,
                equalTo(expected.trim()));

        String actual = Strings.center(value, targetLength, lean);
        assertThat(actual, equalTo(expected));
    }
}

答案 7 :(得分:1)

这是在中心放置字符串的另一种方法。

public static void center(String s, int length, CharSequence ch) {
    /* It works as follows
     * String centerString = String.format("|%" + (length - s.length()) + "s", s);
     * centerString = String.format("%" + -length + "s|", centerString);
     * System.out.println(centerString);
     */

    String centerString = String.format("%-" + length + "s|", String.format("|%" + (length - s.length()) + "s", s));
    System.out.println(centerString);
}

答案 8 :(得分:0)

以下是我如何处理Java中心列标题的示例:

public class Test {
    public static void main(String[] args) {
        String[] months = { "January", "February", "March", "April", "May", "June", "July", "August", "September",
                "October", "November", "December" };

        // Find length of longest months value.
        int maxLengthMonth = 0;
        boolean firstValue = true;
        for (String month : months) {
            maxLengthMonth = (firstValue) ? month.length() : Math.max(maxLengthMonth, month.length());
            firstValue = false;
        }

        // Display months in column header row
        for (String month : months) {
            StringBuilder columnHeader = new StringBuilder(month);
            // Add space to front or back of columnHeader
            boolean addAtEnd = true;
            while (columnHeader.length() < maxLengthMonth) {
                if (addAtEnd) {
                    columnHeader.append(" ");
                    addAtEnd = false;
                } else {
                    columnHeader.insert(0, " ");
                    addAtEnd = true;
                }
            }
            // Display column header with two extra leading spaces for each
            // column
            String format = "  %" + Integer.toString(maxLengthMonth) + "s";
            System.out.printf(format, columnHeader);
        }
        System.out.println();

        // Display 10 rows of random numbers
        for (int i = 0; i < 10; i++) {
            for (String month : months) {
                double randomValue = Math.random() * 999999;
                String format = "  %" + Integer.toString(maxLengthMonth) + ".2f";
                System.out.printf(format, randomValue);
            }
            System.out.println();
        }
    }
}