Java中的文本块(或多行字符串)功能是什么? [英] What is the Text Blocks (or Multiline Strings) feature in Java?

查看:68
本文介绍了Java中的文本块(或多行字符串)功能是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java SE 13引入了 文本块 (或多行字符串)功能.与现有的字符串表示形式有什么区别和相似之处?

Java SE 13 introduced Text Blocks (or Multiline Strings) feature. What are its differences and the similarities with the existing string representation?

推荐答案

什么是文本块?

文本块是多行字符串文字,该功能提供了一种干净的方式来以可预测的方式格式化字符串,而无需使用大多数转义序列.它以""(三个双引号)开头和结尾,例如

What is a text block?

A text block is a multi-line string literal and the feature offers a clean way to format the string in a predictable way, without using most of the escape sequences. It starts and ends with a """ (three double-quotes marks) e.g.

public class Main {
    public static void main(String[] args) {
        String text = """
                <html>
                    <head>
                        <title>Hello World</title>
                    </head>
                    <body>
                        Java rocks!
                    </body>
                </html>""";

        System.out.println(text);
    }
}

输出:

<html>
    <head>
        <title>Hello World</title>
    </head>
    <body>
        Java rocks!
    </body>
</html>

使用传统的字符串表示形式,代码看起来像

With the traditional string representation, the code would look like

public class Main {
    public static void main(String[] args) {
        String text = "<html>\n"
                + " <head>\n"
                + "     <title>Hello World</title>\n"
                + " </head>\n"
                + " <body>\n"
                + "     Java rocks!\n"
                + " </body>\n"
                + "</html>";

        System.out.println(text);
    }
}

另一个 键区别 是:文本块以三个双引号字符开头,后跟一个行终止符,而情况并非如此传统的字符串表示形式.意思是

Another key difference is that a text block begins with three double-quote characters followed by a line terminator which is not the case with the traditional string representation. It means

  1. 文本块不能放在一行上.

  1. The text block can not be put on a single line.

文本块的内容不能在同一行的三个开双引号后面.

The contents of the text block can not follow the three opening double-quotes on the same line.

String str = "Hello World!"; // The traditional string

String textBlock = """
        Hello World!
        """; // The text block

String notAllowed = """Hello World!"""; // Error

// The following code will fail compilation
String notAllowed2 ="""Hello
         World!
        """;

有关缩进的注释:

编译器将整个文本块向左移动,然后保留指定的间距.

The compiler shifts the complete text block to the left and then retains the specified spacing.

String str1 = """
   Hello""";
^^^<-----These three whitespace characters will be retained

演示:

public class Main {
    public static void main(String[] args) {
        // Text block without a line break at the end
        String str1 = """
                Hello""";

        // Text block with a line break at the end
        String str2 = """
                Hello
                """;

        // Text block with three whitespace in the beginning and a line break at the end
        String str3 = """
                   World!
                """;
        System.out.println(str1);
        System.out.println(str2);
        System.out.println(str3);
        System.out.println("Java rocks!");
    }
}

输出:

Hello
Hello

   World!

Java rocks!

只能作为预览功能使用吗?

它作为预览功能在Java SE 13和Java SE 14中仍然可用,并已与Java SE 15进行了标准化.与Java SE 13和14一样,它与任何 Preview功能一样,必须使用-enable-preview 选项(例如

Is it available only as a Preview Feature?

It remained available in Java SE 13 and Java SE 14 as a Preview Feature and has been standardised with Java SE 15. With Java SE 13 and 14, like any Preview Feature, it has to be compiled and executed with --enable-preview option e.g.

要编译:

javac --enable-preview --release 13 Main.java

要执行:

java --enable-preview Main

它们存储在字符串池中吗?

是的,他们是.文本块被编译为与传统 String 值相同的类型,即字节代码不能区分传统 String 值和文本块.

Are they stored in string pool?

Yes, they are. The text blocks are compiled to the same type as that of the traditional String value i.e. the byte code does not distinguish between a traditional String value and text block.

public class Main {
    public static void main(String[] args) {
        String str1 = "Hello World!";
        String str2 = """
                Hello World!""";
        System.out.println(str1 == str2);
    }
}

输出:

true

文本块可以与另一个字符串连接吗?

是的,可以以相同的方式将一个文本块连接到一个传统的字符串值或另一个文本块,将传统的 String 值连接起来.如上所述,字节码不能区分传统的 String 值和文本块.

Can a text block be concatenated with another string?

Yes, a text block can be concatenated to a traditional string value or another text block in the same way, the traditional String values are concatenated. As already described above, the byte code does not distinguish between a traditional String value and text block.

public class Main {
    public static void main(String[] args) {
        String str1 = "Hello ";
        String str2 = """
                World!""";
        String str3 = """
                 Java rocks!
                """;
        System.out.println(str1 + str2);
        System.out.println(str1 + (str2 + str3));
    }
}

输出:

Hello World!
Hello World! Java rocks!

请注意,我在 str1 中的 Hello 之后放置了空格,并在 str3 中的 Java rock!之前放置了另一个空格.

Note that I have put whitespace after Hello in str1 and another whitespace before Java rocks! in str3.

是的,转义序列将以传统方式进行评估,例如

Yes, the escape sequences will be evaluated in the traditional way e.g.

public class Main {
    public static void main(String[] args) {
        String text = """
                <html>
                    <head>
                        <title>Hello World</title>
                    </head>
                    <body>
                        Java\n\t\trocks!
                    </body>
                </html>""";

        System.out.println(text);
    }
}

输出:

<html>
    <head>
        <title>Hello World</title>
    </head>
    <body>
        Java
        rocks!
    </body>
</html>

它支持可替换参数吗?

是的,您可以使用%s $<< replaceable-parameter>> 替换文本块中的参数,如下所示:

Does it support replaceable parameter?

Yes, you can replace a parameter in the text block using %s or $<<replaceable-parameter>> as shown below:

public class Main {
    public static void main(String[] args) {
        String text = """
                What is the distance between %s and %s?""";

        System.out.println(String.format(text, "earth", "moon"));
        System.out.println(String.format(text, "earth", "mercury"));

        // Alternative-1
        text = """
                What is the distance between $celestial1 and $celestial2?""";

        System.out.println(text.replace("$celestial1", "earth").replace("$celestial2", "moon"));

        // Alternative-2 using the deprecated String#formatted
        text = """
                What is the distance between %s and %s?""";
        System.out.println(text.formatted("earth", "moon"));
    }
}

输出:

What is the distance between earth and moon?
What is the distance between earth and mercury?
What is the distance between earth and moon?
What is the distance between earth and moon?

这篇关于Java中的文本块(或多行字符串)功能是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆