Lion
Lion

Reputation: 19027

How to replace a back slash with another character in Java?

I'm trying the following code in Java in which I need to replace a back slash with a forward slash but I can't.

package superpkg;
import java.util.regex.Matcher;

final public class Super
{
    public static void main(String[] args) 
    {
         String string="xxx\\aaa";

         string.replaceAll("\\\\", "/");
         System.out.println(string);

         string.replaceAll(Matcher.quoteReplacement("\\"), "/");
         System.out.println(string);
    }
}

In both the cases, it displays the following output.

xxx\aaa
xxx\aaa

means that the back slash in the given string is not replaced with the forward slash as expected. How can it be achieved?

Upvotes: 0

Views: 1114

Answers (6)

ring bearer
ring bearer

Reputation: 20783

java.lang.String is immutable. So you should assign result of your API call to a new variable.

Upvotes: 1

Michael W
Michael W

Reputation: 3555

    public static void main(String[] args)  
{ 
     String string="xxx\\aaa"; 

     string = string.replaceAll("\\\\", "/"); 

     System.out.println(string); 
} 

Upvotes: 0

Olivier Croisier
Olivier Croisier

Reputation: 6149

Strings are immutable. There is no mean to modify a string in-place, every method called on String returns a new String.

In your code, string.replaceAll(...) returns a String but you don't reassign it to your "string" variable, so the result is lost. Use this instead :

public class Test {
public static void main(String[] args) {
    String string = "xxx\\aaa";
    string = string.replace("\\", "/");
    System.out.println(string);
    }
}

Upvotes: 2

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272487

Strings are immutable in Java. You need to assign the result of replaceAll somewhere:

string = string.replaceAll("\\\\", "/");

Upvotes: 8

GETah
GETah

Reputation: 21409

You are not assigning string its new value. Do this instead string = string.replaceAll("\\\\", "/");

Upvotes: 3

Boiler Bill
Boiler Bill

Reputation: 1940

Strings are immutable so you need to do

string = string.replaceAll("\\\\", "/");

Upvotes: 5

Related Questions