-3

String s=o.replace ("/","\\"); replaces "/" with "\", but what I actually need is to replace it with "\\ "instead.

How can I do so?

ShadowNull
  • 15
  • 5
  • 4
    Use 4 backslashes: "\\\\" –  Feb 02 '15 at 17:07
  • 3
    Are you trying to accomplish something with a Windows-style path? What are you really after? Kind of feels like an [XY Problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – Makoto Feb 02 '15 at 17:09
  • Please try to research before asking questions here. – Pratik Feb 02 '15 at 17:11
  • Question seems fine to me. Please refer to a duplicate if you downvote it for that reason. – vikingsteve Feb 02 '15 at 17:13
  • 1
    possible duplicate of [escaping backslash in java string literal](http://stackoverflow.com/questions/23363241/escaping-backslash-in-java-string-literal) – gknicker Feb 02 '15 at 17:30

2 Answers2

2

you must escape each single "\", so if you want to replace a double backslash use:

String s = o.replace("/", "\\\\");

if you want to replace ALL occurences of "/" kepp the replaceAll()-Method in mind

//EDIT: as said in the comments, replace() also replaces ALL occurences of the String, but replaceAll() can use regex.

Steffen
  • 341
  • 1
  • 12
  • 4
    Actually, `String.replace()` method DOES replace all occurences. The difference is that `replaceAll()` uses regex. – vikingsteve Feb 02 '15 at 17:11
1

Backslash is a reserved char and need to be escaped by one backslash:

\\ means \, so you need 4 in your case.