How to replace “ \ ” with “ \\ ” in java

£可爱£侵袭症+ 提交于 2019-11-26 09:56:48

问题


I tried to break the string into arrays and replace \\ with \\\\ , but couldn\'t do it, also I tried String.replaceAll something like this (\"\\\",\"\\\\\");. I want to supply a path to JNI and it reads only in this way. Can someone help me on this please. Thank you.


回答1:


Don't use String.replaceAll in this case - that's specified in terms of regular expressions, which means you'd need even more escaping. This should be fine:

String escaped = original.replace("\\", "\\\\");

Note that the backslashes are doubled due to being in Java string literals - so the actual strings involved here are "single backslash" and "double backslash" - not double and quadruple.

replace works on simple strings - no regexes involved.




回答2:


You could use replaceAll:

String escaped = original.replaceAll("\\\\", "\\\\\\\\");



回答3:


I want to supply a path to JNI and it reads only in this way.

That's not right. You only need double backslashes in literal strings that you declare in a programming language. You never have to do this substitution at runtime. You need to rethink why you're doing this.



来源:https://stackoverflow.com/questions/7535317/how-to-replace-with-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!