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

wyjściowa:Jak wyśrodkować ciąg za pomocą String.format?

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

Chcę wyjście do centrum. Jeśli nie użyję flagi "-", wynik zostanie wyrównany w prawo.

Nie znalazłem flagi, aby wyśrodkować tekst w interfejsie API.

This artykuł zawiera informacje o formacie, ale nic w centrum nie uzasadnia.

+0

Dane wyjściowe są w rzeczywistości tabelami, więc niektóre pytania powodują nieprawidłowe wyświetlanie tabeli. – rana

+3

Zobacz '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) ** lub ** [http://www.java2s.com/Code/Java/Data-Type/CentersaStringinalargerStringofsizesizeusing thespacecharacter .htm] (http://www.java2s.com/Code/Java/Data-Type/CentersaStringinalargerStringofsizesizeusing the spacechar.htm) – ecle

+0

@eee to StringUtils w standardowej bibliotece? – rana

Odpowiedz

16

Szybko zhakowałem to. Możesz teraz użyć StringUtils.center(String s, int size) w 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

dziękuję za odpowiedź; – rana

+1

Będę trzymać się StringUtils od Apache commons lang, ponieważ łatwo jest zintegrować to za pomocą maven – rana

+0

@rana, świetny pomysł! –

4

Oto odpowiedź za pomocą apache commons lang StringUtils.

Należy pamiętać, że należy dodać plik jar do ścieżki budowania. Jeśli używasz maven, upewnij się, że dodasz wspólny język w zależnościach.

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

Ta odpowiedź jest bardziej odpowiednia, ponieważ używa znanej Biblioteki do tego celu –

+1

uzgodniona @ 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

Świetna odpowiedź! Być może warto zastanowić się nad nazwaniem małych nazw metod, a użycie wielkich liter sprawia, że ​​jest to klasa, a nie metoda. –

0

Oto przykład jak ja przejrzeniu elementów centrowanie nagłówki kolumn w języku 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

Grałem około eleganckie odpowiedź Mertuarez za powyżej postanowił pisać moją wersję.

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

wyjściowa:

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 | 

Praktyczne różnice w Mertuarez kodzie:

  1. Kopalnia robi matematyka górę przodu i podejmuje ostateczną wyśrodkowany napis w jednym ujęciu zamiast tworzenia zbyt- długi ciąg, a następnie pobranie z niego podciągu. Zakładam, że jest to nieco bardziej wydajne, ale nie przetestowałem go.
  2. W przypadku tekstu, który nie może być perfekcyjnie wyśrodkowany, moje konsekwentnie umieszcza go po połowie znaku w lewo, zamiast umieszczać go połową znaku w prawej połowie czasu.
  3. W przypadku tekstu dłuższego niż podana długość, kopalnia konsekwentnie zwraca podany fragment o określonej długości, który jest zakorzeniony na początku oryginalnego tekstu.
Powiązane problemy