2012-12-01 40 views
0

如何做一個格式如下:的Java:一個列表字符串格式

從這:

1: My street 
2: 1232321 
3: Hello there world! 
4: A really really really long word! 

要這樣:

1:       My street 
2:        1232321 
3:     Hello there world! 
4: A really really really long word! 

我認爲這是與字符串.format()和一堆隨機字符在裏面!

+1

你有什麼'String.format()'? –

+0

我認爲這可能是一個重複或至少非常類似的問題[this](http://stackoverflow.com/questions/6640184/java-output-right-alignment)。看看那個。 –

回答

3

你可以先拆你的字符串得到1:My Street分開,然後進行格式化: -

String str = "1: My street"; 
String str2 = "3: Hello there world!"; 

String[] arr = str.split("(?<=:) "); 
String[] arr2 = str2.split("(?<=:) "); 

System.out.printf("%s%30s\n", arr[0], arr[1]); 
System.out.printf("%s%30s", arr2[0], arr2[1]); 

輸出: -

1:      My street 
3:   Hello there world! 

你可以用String#substring方法做到這一點也,分別得到兩部分。

System.out.printf("%s%30s\n", str.substring(0, 2), str.substring(3)); 
+0

完美!謝謝:) –

+0

@KarlMorrison ..不客氣:) –