How to center a string using String.format?

后端 未结 9 1597
陌清茗
陌清茗 2020-11-30 12:28
public class Divers {
  public static void main(String args[]){

     String format = \"|%1$-10s|%2$-10s|%3$-20s|\\n\";
     System.out.format(format, \"FirstName\",         


        
9条回答
  •  半阙折子戏
    2020-11-30 12:44

    I was playing around with Mertuarez's elegant answer above and decided to post my version.

    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) + "|");
                }
            }
        }
    }
    

    Output:

    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  | 
    

    Practical differences from Mertuarez's code:

    1. Mine does the math up-front and makes the final centered string in one shot instead of making a too-long string and then taking a substring from it. I assume this is slightly more performant, but I did not test it.
    2. In the case of text that can't be perfectly centered, mine consistently puts it half a character to the left rather than putting it half a character to the right half of the time.
    3. In the case of text that's longer than the specified length, mine consistently returns a substring of the specified length that's rooted at the beginning of the original text.

提交回复
热议问题