LeoPro
LeoPro

Reputation: 41

How to replace a space exactly by "\_" in java String?

I have a string with space and I want that space replace by "\_" . For example here is my code

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

And the result of example is: "Bill_Gates" not "Bill\_Gates". When I try to do like this

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

The result of example is: "Bill\\_Gates" not "Bill\_Gates"

Upvotes: 4

Views: 4198

Answers (3)

Bruce
Bruce

Reputation: 8849

You need to use replaceAll(" ","\\\\_") instead of replaceAll(" ","\\_"). Because '\\' is a literal. It will be compiled as '\' single slash. When you pass this to replaceall method. It will take first slash as escaping character for "_". If you look inside replaceall method

    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++;

When it finds a single slash it will replace next character of that slash. So you have to input "\\\\_" to replace method. Then it will be processed as "\\_". Method will look first slash and replace second slash. Then it will replace underscore.

Upvotes: 5

Ankur Singhal
Ankur Singhal

Reputation: 26077

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

output

Bill\_Gates

Upvotes: 1

thegauravmahawar
thegauravmahawar

Reputation: 2823

Try:

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

Upvotes: 1

Related Questions