2011-11-16 18 views
11
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)); 
    } 
} 

uscita:Come centrare una stringa usando String.format?

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

voglio l'uscita per essere centrato. Se non utilizzo il flag '-', l'output sarà allineato a destra.

Non ho trovato un flag per centrare il testo nell'API.

This L'articolo contiene alcune informazioni sul formato, ma nulla sul centro giustifica.

+0

L'output è in realtà una tabella, quindi qualche domanda di motivazione non mostra correttamente la tabella. – rana

+3

Vedere 'StringUtils' [http://stackoverflow.com/questions/2709993/how-to-center-string-output-using-printf-and-variable-width-java](http://stackoverflow.com/questions/2709993/how-to-center-string-output-using-printf-and-variable-width-java) ** o ** [http://www.java2s.com/Code/Java/Data-Type/CentersaStringinalargerStringofsizesizeusingthespacecharacter .htm] (http://www.java2s.com/Code/Java/Data-Type/CentersaStringinalargerStringofsizesizeusingthespacecharacter.htm) – ecle

+0

@eee è StringUtils nella libreria standard? La libreria – rana

risposta

16

Ho subito risolto il problema. È ora possibile utilizzare StringUtils.center(String s, int size) in 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(); 
    } 
} 
+0

grazie per la risposta; – rana

+1

Mi attaccherò a StringUtils da apache commons lang poiché è facile integrarlo usando Maven – rana

+0

@rana, Great Idea! –

4

Ecco la risposta utilizzando apache commons lang StringUtils.

Si noti che è necessario aggiungere il file jar al percorso di generazione. Se stai usando Maven, assicurati di aggiungere Common Lang nelle dipendenze.

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

Questa risposta è più adatta, perché utilizza una libreria ben nota a questo scopo –

+1

concordata @PauloOliveira –

12
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

Ottima risposta! Potrebbe voler prendere in considerazione la possibilità di rendere minuscoli i nomi dei metodi, la capitalizzazione fa sembrare che sia una classe piuttosto che un metodo. –

0

Ecco un esempio di come ho gestito la centratura intestazioni delle colonne in 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(); 
     } 
    } 
} 
0

stavo giocando intorno con elegante risposta di Mertuarez sopra e deciso di pubblicare la mia versione.

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

uscita:

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 | 

differenze pratiche dal codice del Mertuarez:

  1. miniera fa la matematica up-front e rende la stringa finale centrato in un solo colpo, invece di fare un troppo- stringa lunga e poi prendere una sottostringa da esso. Presumo che questo sia leggermente più performante, ma non l'ho provato.
  2. Nel caso di un testo che non può essere perfettamente centrato, il mio mette costantemente mezzo personaggio a sinistra piuttosto che metterlo mezzo personaggio nella metà destra del tempo.
  3. Nel caso di testo più lungo della lunghezza specificata, il mio restituisce costantemente una sottostringa della lunghezza specificata che è radicata all'inizio del testo originale.
Problemi correlati