Java 7 - 多行字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4581338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 07:03:15  来源:igfitidea点击:

Java 7 - Multiline strings

javajava-7multilinestring

提问by Mike

I've read that multiline string literals were proposed to be added in Java 7.

我读过有人建议在 Java 7 中添加多行字符串文字。

Although I can't find any documentation saying definitely that they have been. I'd like to know if they are, because this is something I'd consider switching versions for.

虽然我找不到任何文件明确说明他们已经存在。我想知道它们是否是,因为这是我考虑切换版本的东西。

采纳答案by Jo?o Silva

Multiline string literals are not going to be added to JDK 7. You can check Project Coin's homepagefor a list of language changes.

多行字符串文字不会添加到 JDK 7。您可以查看 Project Coin 的主页以获取语言更改列表。

However, you can use Scala, which does support multiline string literals using triple quotes:

但是,您可以使用 Scala,它支持使用三重引号的多行字符串文字:

var s = """Hello
      World"""

回答by HyperNeutrino

Multiline strings were not added into Java (even as of Java 8, the newest current version), and probably will never be added to Java. However, you can add multiple strings together like so:

多行字符串没有添加到 Java 中(即使从最新的当前版本 Java 8 开始),并且可能永远不会添加到 Java 中。但是,您可以像这样将多个字符串添加在一起:

String greeting = "Hello " + 
    "world! " + 
    "This is a multiline string.";

Or, if you want the multiline line breaks to actuallystart a new line, insert "\n" to the end of each line.

或者,如果您希望多行换行符实际开始一个新行,请在每行末尾插入“\n”。

回答by bradylange

Following Java's coding conventions Strings should be concatenated like:

遵循 Java 的编码约定,字符串应该像这样连接:

String str = "Long text line " 
             + "more long text.";

Make sure the +operator always begins the next line for readability.
See: Code Conventions for the Java Programming Language: 4. Indentation

确保+操作员始终从下一行开始以提高可读性。
请参阅:Java 编程语言的代码约定:4. 缩进

回答by ZhekaKozlov

Multiline strings are supported in Java since JDK 13. They are called text blocks:

从 JDK 13 开始,Java 就支持多行字符串。它们被称为文本块

String html = """
          <html>
              <body>
                  <p>Hello, world</p>
              </body>
          </html>
          """;

Note, this is a preview feature. But I hope it will become a permanent feature in one of the next releases (JDK 14-15).

请注意,这是一个预览功能。但我希望它会在下一个版本(JDK 14-15)中成为永久功能。