java 在java中用反斜杠转义空间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32216827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 19:50:42  来源:igfitidea点击:

Escape space with backslash in java

javastringreplaceescapingreplaceall

提问by

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"

“/Users/TD/San Diego”到“/Users/TD/San Diego”

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

字符串中的任何其他空格也需要替换为“\”

采纳答案by Elliott Frisch

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.replacelike

另一种选择是使用String.replace

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

which outputs the same.

输出相同。

回答by Martin Zeitler

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

建议的解决方案对我不起作用(在 Android Java 中)。

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

所以这是我想出的,经过多次尝试:

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