打印一个格式化的字符串。
打印一个格式化的字符串。
已关闭:这个问题不符合Stack Overflow的指南,目前不接受回答。
要求提问者对代码的问题有最基本的理解,必须包含尝试的解决方案,说明它们为何无法工作,以及期望结果。另请参见:Stack Overflow问题清单
改进此问题
代码是:
public static void main(String[] args) { // TODO Auto-generated method stub String str = "" + "" + "" + " " + "" + " %s" + " " + " "; String str1 = String.format(str, "Home","Hallo"); System.out.println(str1); }
我想要把str1
打印成以下形式:
//The str1 should need to print like this Hallo
这是可能的吗?
admin 更改状态以发布 2023年5月21日
如果您想要避免在大型 HTML 字符串中手动添加大量的 \n
,那么您可以使用 dom4j
包中的 OutputFormat.createPrettyPrint()
:
public String prettyHTMLPrint (String html) { if (html==null || html.isEmpty()) { throw new RuntimeException("xml null or blank in prettyHTMLPrint()"); } StringWriter sw; try { OutputFormat format = OutputFormat.createPrettyPrint(); format.setSuppressDeclaration(true); org.dom4j.Document document = DocumentHelper.parseText(html); sw = new StringWriter(); XMLWriter writer = new XMLWriter(sw, format); writer.write(document); } catch (Exception e) { throw new RuntimeException("Error pretty printing html: " + e, e); } return sw.toString(); }
对于您的示例,它会打印出格式化后的 HTML:
Home Hello
String str = "\n" + " \n" + "\n" + " %s\n" + " \n" + " \n" + " \n" + " %s\n" + " \n" + " \n";
这就是你想要的…如果你在windows系统上,可能需要在\n后面添加一个额外的\r。
\n
被称为换行符,\r
被称为回车符。在Unix和Windows系统中,\n
是标准的换行符,但是在Windows下的一些程序可能需要回车符来正确显示你的字符串。
System.getProperty("line.separator");
将在Unix系统上返回\n
,在Windows系统上返回\n\r
,它只是返回执行此命令的操作系统的标准"行分隔符"。