Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1300
  • Last Modified:

Java String replace

If a string contains \\\\ (4 backslashes) is there anyway to replace that string with \ (one backslash)?
Tried the following:
strtest.replace("\\\\", "\") - unclosed String literal error
strtest.replace("\\\\", "\\") - hoped it would see the first back slash as an escape but replaces with 2 \\

Thanks for any ideas.
0
edwardui
Asked:
edwardui
  • 2
1 Solution
 
RishadanPortCommented:
You have to understand that:

"\\"  --> means "\"

Backslash is a special character, so doing this:

"\"  is incorrect syntax... Change it to "\\"

Or, use the @ sign before the quotation, then it is ok for you to not need to use double backslashes

@"\"  is ok
0
 
mbodewesCommented:
Backslash is an escape character, this should work:

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

So you've got 4 escaped backslashes, replaced by a single escaped backslash (!).
0
 
RishadanPortCommented:
strtest.replace(@"\\\\", @"\");
0
 
edwarduiAuthor Commented:
Thank you for the replies.  
strtest.replace("\\\\\\\\", "\\"); was what i was looking for.
I don't think @ works in java.  Think i remember using that in .NET though
Thanks
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now