Solved

Java String replace

Posted on 2008-10-01
4
1,292 Views
Last Modified: 2012-06-22
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
Comment
Question by:edwardui
  • 2
4 Comments
 
LVL 6

Expert Comment

by:RishadanPort
ID: 22619658
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
 
LVL 9

Accepted Solution

by:
mbodewes earned 500 total points
ID: 22619661
Backslash is an escape character, this should work:

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

So you've got 4 escaped backslashes, replaced by a single escaped backslash (!).
0
 
LVL 6

Expert Comment

by:RishadanPort
ID: 22619695
strtest.replace(@"\\\\", @"\");
0
 

Author Comment

by:edwardui
ID: 22619967
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
The viewer will learn how to implement Singleton Design Pattern in Java.

896 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now