Backslash space exception in java

I want to replace spaces from a path string. I tried below but it doesn't seem to work:

String path = "/Users/TD/San Diego";
path=path.replaceAll(" ","\\ ");
System.out.println(path);

The goal is to convert

"/ Users / TD / San Diego" at "/ Users / TD / San \ Diego"

Any additional space from the string must also be replaced with "\"

+5
source share
2 answers

You can change

path = path.replaceAll(" ", "\\ ");

to avoid backslash

path = path.replaceAll(" ", "\\\\ ");

When I do this, I get (requested)

/Users/TD/San\ Diego

Another option would be to use String.replacefor example

path = path.replace(" ", "\\ ")

which outputs the same.

+5
source

( Android Java).

:

path = path.replace(" ", (char) 92 + " ");
0

All Articles