有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用字符串将字符串居中。总体安排

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这篇文章有一些关于格式的信息,但没有任何关于格式的信息


共 (6) 个答案

  1. # 1 楼答案

    下面是使用apache commons lang StringUtils的答案

    请注意,您必须将jar文件添加到构建路径中。如果您使用的是maven,请确保在依赖项中添加commons lang

    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));
      }
    }
    
  2. # 2 楼答案

    自Java 11以来的“一行程序”

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

    其中:

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

    自Java 8以来

    Java8没有" ".repeat(10)方法。所以

    • 只需将" ".repeat(10)替换为Java8模拟。见https://stackoverflow.com/a/57514604/601844,以及

    • 使用与Java 11相同的☝️) alg:

        int spaceSize = n - s.length();
        int prefixSize = spaceSize / 2;
        int suffixSize = (spaceSize + 1) / 2
        return n > s.length()
             ? space(prefixSize) + s + space(suffixSize)
             : s;
      }
      
      String space(int spaceSize) {
        return generate(() -> " ").limit(spaceSize).collect(joining());
      }
      
  3. # 3 楼答案

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

    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();
        }
    }
    
  4. # 4 楼答案

    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);
                System.out.println(center(s.substring(0, j),i));
            }
        }
    }
    
  5. # 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   "
    }
    

    我认为这是一个非常简洁的解决方案,值得一提

  6. # 6 楼答案

    我在玩弄上面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. 对于长度超过指定长度的文本,My始终返回指定长度的子字符串,该子字符串的根位于原始文本的开头