常用的转义字符

image

1. 字符串中包含双引号”要转义,写成\"

// JSON数据中需要转义引号
String json = "{\"name\":\"张三\",\"age\":20}";
System.out.println(json);  
// 输出:{"name":"张三","age":20}

2.字符串中包含单引号',可以转义也可以不转义,要转可写成\'

String str2 = "It\'s Java time!";
System.out.println(str2);
//输出:It's Java time! 

3.文件转义路径

// Windows路径
String winPath = "C:\\Users\\Administrator\\Desktop\\file.txt";
System.out.println(winPath);  // C:\Users\Administrator\Desktop\file.txt

// 不需要转义的替代方案
String winPath2 = "C:/Users/Administrator/Desktop/file.txt";  // ✅ 使用正斜杠

 

posted @ 2026-01-22 16:23  小胡666  阅读(44)  评论(0)    收藏  举报
39
0