Rit*_*hik 5 java string java-15
刚刚在 Java 15 中遇到了一个新特性,即“文本块”。我可以假设一个变量可以通过与“+”运算符连接来添加到文本块中,如下所示:
String html = """
<html>
<body>
<p>Hello, """+strA+"""</p>
</body>
</html>
""";
Run Code Online (Sandbox Code Playgroud)
但是他们是否提供了任何方式,以便我们可以以在许多其他语言中流行的方式添加变量,如下所示:
String html = """
<html>
<body>
<p>Hello, ${strA}</p>
</body>
</html>
""";
Run Code Online (Sandbox Code Playgroud)
这个问题可能听起来很愚蠢,但在某些情况下可能很有用。
Ale*_*rov 12
Java 15 不支持直接在文本块内插入,也不支持纯字符串文字。
Java 15 中的解决方案是使用String.formatted()method:
String html = """
<html>
<body>
<p>Hello, %s</p>
</body>
</html>
""".formatted(strA);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1340 次 |
| 最近记录: |