16

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
David Prun
  • 8,203
  • 16
  • 60
  • 86

4 Answers4

34

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

You could use replaceAll:

String escaped = original.replaceAll("\\\\", "\\\\\\\\");
Pshemo
  • 122,468
  • 25
  • 185
  • 269
1

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
0

It can be quite an adventure to deal with the "\" since it is considered as an escape character in Java. You always need to "\" a "\" in a String. But the fun begins when you want to use a "\" in regex expression, because the "\" is an escape character in regex too. So for a single "\" you need to use "\\" in a regex expression.

here is the link where i found this information: https://www.rgagnon.com/javadetails/java-0476.html

I had to convert '\' to '\\'. I found somewhere that we can use:

filepathtext = filepathtext.replace("\\","\\\\"); 

and it works. Given below is the image of how I implemented it.

https://i.stack.imgur.com/LVjk6.png

Gudmundur Orn
  • 2,003
  • 2
  • 23
  • 31