Escape space with backslash in java
Asked Answered
Z

2

12

I want to replace spaces from path string. I tried below but doesn't seems to be working :

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

Goal is to convert

"/Users/TD/San Diego" to "/Users/TD/San\ Diego"

Any further space from string also needs to be replaced with "\ "

Zincograph answered 26/8, 2015 at 1:58 Comment(1)
Why? They work as-is.Riocard
P
10

You could change

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

to escape the backslash

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

When I do that, I get (the requested)

/Users/TD/San\ Diego

Another option would be using String.replace like

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

which outputs the same.

Phenomenology answered 26/8, 2015 at 2:1 Comment(0)
H
0

The suggested solution did not work for me (in Android Java).

So this is what I've came up with, after quite a few attempts:

path = path.replace(" ", (char) 92 + " ");
Heartland answered 13/4, 2019 at 5:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.