0

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?

Lion
  • 18,729
  • 22
  • 80
  • 110

6 Answers6

8

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

string = string.replaceAll("\\\\", "/");
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
5

Strings are immutable so you need to do

string = string.replaceAll("\\\\", "/");
Boiler Bill
  • 1,900
  • 1
  • 22
  • 32
3

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

GETah
  • 20,922
  • 7
  • 61
  • 103
2

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);
    }
}
Olivier Croisier
  • 6,139
  • 25
  • 34
1

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

ring bearer
  • 20,383
  • 7
  • 59
  • 72
0
    public static void main(String[] args)  
{ 
     String string="xxx\\aaa"; 

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

     System.out.println(string); 
} 
Michael W
  • 3,515
  • 8
  • 39
  • 62