user1075958
user1075958

Reputation: 201

Using String.replace() to replace slashes ie "\"

I have a string like C:\Users\temp\index.html and want to replace "\" with "\\". I have tried the following:

 str= str.replace("\", "\\");

.. but Eclipse keeps suggesting that I add arguments to the replace method.

Any help would be appreciated.

Upvotes: 0

Views: 106

Answers (4)

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

Try this,

str = str.replace("\\", "\\\\");

As "\" nullifies the effect of symbols which has special meaning in the language.

Upvotes: 0

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41200

String str="C:\Users\temp\index.html";
str = str.replace("\\", "\\\\");
System.out.println(str);

Upvotes: 0

mellamokb
mellamokb

Reputation: 56769

You need to escape the slash characters:

str = str.replace("\\", "\\\\");

Upvotes: 1

Francis Upton IV
Francis Upton IV

Reputation: 19443

You need to escape your \. Use the \ character to escape. The \ is necessary to escape both \ and ".

str.replace("\\", "\\\\");

Upvotes: 0

Related Questions