Search code examples
javastringbackslashslashreplaceall

Change a "\" to a "/"


I'm looking for a simple piece of code that will change all the backslashes in a string to forward slashes using java.

I tried this: word.replaceAll("\","/");

but it will not work. Anyone have a quick fix for this?

Thanks

P.S. I also just noticed that pretty much none of my string operations are working. I tried things like toUpperCase() and nothing happened to the string?!?


Solution

  • replaceAll() is the wrong method to use in this case, because it uses regular expressions to match.

    You want the simpler replace() method that replaces literals. Try this:

    word = word.replace("\\","/");
    

    Notes:

    1. You have to escape the backslash with another backslash, ie "\\" is how you code a String that is a single backslash
    2. String are immutable - String methods return a new String with the result... they don't change the String. That's why you need to code it like myString = myString.someMethod();