如何用" \ _"完全替换空格在java String中?

时间:2015-11-05 04:27:40

标签: java string replace replaceall

我有一个包含空格的字符串,我希望用"\_"替换该空格 。例如,这是我的代码

String example = "Bill Gates";
example = example.replaceAll(" ","\\_");    

例子的结果是:" Bill_Gates"不是"比尔\ _盖茨"。当我尝试这样做时

String example = "Bill Gates";
example = example.replaceAll(" ","\\\\_");

例子的结果是:"比尔\\ _盖茨"不是"比尔\ _盖茨"

3 个答案:

答案 0 :(得分:2)

您需要使用replaceAll(" ","\\\\_")代替replaceAll(" ","\\_")。因为'\\'是文字。它将被编译为'\'单斜杠。将此传递给replaceall方法时。它将第一个斜杠作为“_”的转义字符。如果您查看replaceall方法

    while (cursor < replacement.length()) {
        char nextChar = replacement.charAt(cursor);
        if (nextChar == '\\') {
            cursor++;
            if (cursor == replacement.length())
                throw new IllegalArgumentException(
                    "character to be escaped is missing");
            nextChar = replacement.charAt(cursor);
            result.append(nextChar);
            cursor++;

当找到一个斜杠时,它将替换该斜杠的下一个字符。所以你必须输入“\\\\ _”来替换方法。然后它将被处理为“\\ _”。方法将首先看斜杠并替换第二个斜杠。然后它将取代下划线。

答案 1 :(得分:1)

尝试:

String example = "Bill Gates";
example = example.replaceAll(" ","\\\\_");   
System.out.println(example);

答案 2 :(得分:1)

public static void main(String[] args) {
        String example = "Bill Gates";
        example = example.replaceAll(" ", "\\\\_");
        System.out.println(example);
    }

<强>输出

Bill\_Gates