【发布时间】:2019-09-20 14:34:06
【问题描述】:
我刚刚尝试了 Java 13 中的新文本块功能,遇到了一个小问题。
我已阅读this article from Jaxcenter。
右三引号会影响格式。
String query = """
select firstName,
lastName,
email
from User
where id= ?
""";
System.out.println("SQL or JPL like query string :\n" + query);
上述格式效果很好。为了与结束分隔符 (""") 对齐,多行字符串在每行之前都留有空格。
但是当我尝试比较以下两个文本块字符串时,它们在输出控制台中的格式相同,但它们不等于,即使在stripIntent 之后也是如此。
String hello = """
Hello,
Java 13
""";
String hello2 = """
Hello,
Java 13
""";
System.out.println("Hello1:\n" + hello);
System.out.println("Hello2:\n" + hello);
System.out.println("hello is equals hello2:" + hello.equals(hello2));
System.out.println("hello is equals hello2 after stripIndent():" + hello.stripIndent().equals(hello2.stripIndent()));
输出控制台是这样的:
hello is equals hello2:false
hello is equals hello2 after stripIndent():false
我不确定哪里错了,或者这是文本块设计的目的?
更新:只需打印 hello2 stripIntent,
System.out.println("hello2 after stripIntent():\n" + hello2.stripIndent());
stripIntent 按预期不删除每行前的空格。
更新:在阅读了相关的java文档后,我认为在文本块编译后,它应该已经剥离了块中行的左意图。 stripIntent 用于文本块的目的是什么?我知道在普通字符串上使用它很容易理解。
完整代码为here。
【问题讨论】:
-
文章指出“在第二步中,由于代码格式的原因,空格被删除。它被标记为结束三个引号的位置。这允许您在代码中放置文本块以便它匹配其余的代码格式”。这让我相信,由于结束
"""的位置不同,空格存在差异。您是否对此进行了调试并查看了运行时的变量? -
只打印 stripIntent 结果,hello2 中每行之前的空格不会按预期删除。
-
我不明白这个问题,两个字符串是不同的(
hello删除了 4 个空格;hello2没有);而且,因为有一个额外的(空)行,stripIndent()什么都不做(我相信它已经在 input 行上使用了 - 我希望hello.stripIndent().equals(hello)与hello2相同) -
@CarlosHeuberger 我有点困惑 stripIntent 如何在文本块上工作,line#89 它在正常字符串中按预期工作。
-
阅读它的documentation,其实就是对齐文本块的方法——就是文本块中文本缩进的逻辑(总结一下每 行开头,并从 每个 行开头删除该数量的空格)