java中的字符串替换问题
Stringstr="/D:/Users/Administrator/Workspaces/MyEclipse%208.51/work/work/.metadata/.m...
String str = "/D:/Users/Administrator/Workspaces/MyEclipse%208.51/work/work/.metadata/.me_tcat7/webapps/wanZhuangWuDang3/RoleMenus/";
System.out.println(str.replaceAll("/", "\\\\"));
结果:
\D:\Users\Administrator\Workspaces\MyEclipse%208.51\work\work\.metadata\.me_tcat7\webapps\wanZhuangWuDang3\RoleMenus\
为什么:?
String str = "/D:/Users/Administrator/Workspaces/MyEclipse%208.51/work/work/.metadata/.me_tcat7/webapps/wanZhuangWuDang3/RoleMenus/";
System.out.println(str.replaceAll("/", "\\"));
报Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1 展开
System.out.println(str.replaceAll("/", "\\\\"));
结果:
\D:\Users\Administrator\Workspaces\MyEclipse%208.51\work\work\.metadata\.me_tcat7\webapps\wanZhuangWuDang3\RoleMenus\
为什么:?
String str = "/D:/Users/Administrator/Workspaces/MyEclipse%208.51/work/work/.metadata/.me_tcat7/webapps/wanZhuangWuDang3/RoleMenus/";
System.out.println(str.replaceAll("/", "\\"));
报Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1 展开
1个回答
展开全部
在java中\用\\表示,2个\就用4个\表示
你的\\代表1个\,在程序中不被解析,需要转义处理,于是再多2个\,否则出错
追问
在替换的时候,\\代表一个\,而java中,字符串如果是这样:
\D:\Users\Administrator\Workspaces\MyEclipse%208.51
那么他的存储将会是这样:
\\D:\\Users\\Administrator\\Workspaces\\MyEclipse%208.51
所以我们应该用\\去替换一个/,而产生一个\由\\,所以写成\\\\
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询