【问题标题】:How to print an already formatted String in Java如何在 Java 中打印已经格式化的字符串
【发布时间】:2013-02-02 20:10:58
【问题描述】:

我有一个已经缩进的段落。例如

Hello:
     Hi every body

现在我想用 Java 打印它。使用System.out.println 我必须把这个函数放在每一行。当你在 python 中使用 print 时,我该怎么做,你只需在它周围加上一个 " 并且它已经准备好了。

【问题讨论】:

    标签: java println system.out


    【解决方案1】:

    像这样格式化字符串是一种方法:

    "Hello:\n\tHi every body"
    

    【讨论】:

    • 对于那些不知道的人:\n 是一个新行,\t 是一个 TAB。好答案,点赞。
    【解决方案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!");
    

    【讨论】:

      【解决方案3】:

      您可以使用\n 等特殊字符作为换行符。

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

      【讨论】:

        【解决方案4】:

        当然,您只需使用换行符和制表符转义序列 - \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

        玩一玩,你就明白了

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-06-21
          • 1970-01-01
          • 1970-01-01
          • 2019-05-01
          • 1970-01-01
          • 1970-01-01
          • 2013-08-29
          相关资源
          最近更新 更多