2013-02-02 74 views
1

我有一段已經縮進的段落。例如如何在Java中打印已格式化的字符串

Hello: 
    Hi every body 

現在我想用Java打印這個。使用System.out.println我必須把這個函數放在每一行中。我該怎麼辦,當你使用蟒紋,你只是把「圍繞它,它喜歡和它已經準備好

回答

2

你已經得到一個String.format方法,返回一個字符串formatted -

String str = String.format("%s%n%20s", "Hello", "Hi everyone!"); 
System.out.println(str); 

%n字符串格式化用於打印newline字符。

%20s將右鍵縮進字符串,並將採取20字符空間。


如果你想打印格式的字符串,而不是將其存儲,您可以使用System.out.format: -

System.out.format("%s%n%20s", "Hello", "Hi everyone!"); 
0

當然,你只需要使用換行和製表轉義序列 - \t\n

這裏有一個簡單例如:

//Note: Text content in the code blocks is automatically word-wrapped 
import java.io.*; 

class Tabs { 
    public static void main(String[] args) { 
    try { 
     String t = "\t\t"; 
     PrintStream ps = new PrintStream("tabs.txt"); 
     ps.print("A" + t + "B"); 
     ps.print("C\t\tD"); 
    } catch(Exception e) { 
     System.err.println(e); 
    } 
    } 
} 

source

參見 - Printing with "\t" (tabs) does not result in aligned columns

玩它,你會發現它

2

你可以使用特殊字符如\n換行。

System.out.println("Hello:\n  Hi everybody"); 
4

格式化這樣的字符串是單向的:

"Hello:\n\tHi every body" 
+1

對於那些我不知道它:'\ n'是一個新行,'\ t'是一個TAB。好的答案,upvoted。 –