David Prun
David Prun

Reputation: 8453

How to replace " \ " with " \\ " in java

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.

Upvotes: 17

Views: 83524

Answers (4)

Vishal Khandate
Vishal Khandate

Reputation: 1

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.sstatic.net/LVjk6.png

Upvotes: 0

Bibin Mathew
Bibin Mathew

Reputation: 31

You could use replaceAll:

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

Upvotes: 3

user207421
user207421

Reputation: 311055

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.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1503729

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.

Upvotes: 35

Related Questions