jdk17新特性——文本块(即多行的字符串)增强
目录
- 一、文本块(即多行的字符串)概述
- 二、文本块(即多行的字符串)示例
- 2.1、jdk17之前 多行字符串处理方式
- 2.2、jdk17及以后版本 多行字符串处理方式
- 2.3、注意事项
- 三、文本块(即多行的字符串)转义字符示例
- 3.1、jdk17及以后版本 多行字符串的转义字符处理方式示例一
- 3.2、jdk17及以后版本 多行字符串的转义字符处理方式示例二
- 四、文本块(即多行的字符串)变量替换示例
一、文本块(即多行的字符串)概述
-
文本块功能,文本块指多行的字符串,使用连续的三个双引号来包围一段带换行的文字,它避免了换行转义的需要,并支持Stringformat。
-
同时添加了两个新的转义字符
\ 置于行尾,用来将两行连接为一行\s 单个空白字符
-
文本块功能在idk13的JEP 355: Text Blocks (Preview)作为预览特性引入,并在idk14的JEP 368: Text BlocksSecond Preview)第二次预览。最终在idk15的JEP 378: Text Blocks成为正式特性
二、文本块(即多行的字符串)示例
2.1、jdk17之前 多行字符串处理方式
-
jdk17之前 多行字符串处理方式代码示例
package com.xz.jdk17.day2;/*** @author: xz* @since: 2024/1/23 22:09* @description: jdk17之前 多行字符串处理方式*/ public class Test1 {public static void main(String[] args) {String html ="<html>\n" +"<body>\n"+"<h1>Hello World!</h1>\n" +"</body>\n"+"</html>\n";System.out.println(html);} }
-
输出结果
2.2、jdk17及以后版本 多行字符串处理方式
-
jdk17及以后版本 多行字符串处理方式代码示例
package com.xz.jdk17.day2;/*** @author: xz* @since: 2024/1/23 22:13* @description: jdk17及以后版本 多行字符串处理方式*/ public class Test2 {public static void main(String[] args) {String html ="""<html><body><h1>Hello World!</h1></body></html>""";System.out.println(html);} }
-
输出结果
2.3、注意事项
- 前一个"""之后要换行,否则编译不过。
- 后一个"““可以不换行,直接写在最后一个字符之后,此时文本的最后没有换行符;如果后一个””"选择换一行写,就代表文本最后是一个换行符。
三、文本块(即多行的字符串)转义字符示例
3.1、jdk17及以后版本 多行字符串的转义字符处理方式示例一
-
jdk17及以后版本 多行字符串的转义字符处理方式代码示例
package com.xz.jdk17.day2;/*** @author: xz* @since: 2024/1/23 22:15* @description: jdk17及以后版本 多行字符串处理方式 转义字符*/ public class Test3 {public static void main(String[] args) {String str ="""hello world,\hello java,\作者:xz。hello python,\作者:xz。""";System.out.println(str);} }
-
输出结果
3.2、jdk17及以后版本 多行字符串的转义字符处理方式示例二
-
jdk17及以后版本 多行字符串的转义字符处理方式代码示例
package com.xz.jdk17.day2;/*** @author: xz* @since: 2024/1/23 22:19* @description:*/ public class Test4 {public static void main(String[] args) {String str ="""hello world\s,hello java\s,hello python\s,作者:xz\s。""";System.out.println(str);} }
-
输出结果
四、文本块(即多行的字符串)变量替换示例
-
文本块(即多行的字符串)变量替换代码示例
package com.xz.jdk17.day2;/*** @author: xz* @since: 2024/1/23 22:32* @description: jdk17及以后版本 多行字符串变量处理方式*/ public class Test5 {public static void main(String[] args) {String html ="""<html><body><h1>%s</h1></body></html>""";System.out.println(String.format(html,"作者:xz"));} }
-
输出结果