Solved

Java String replace

Posted on 2008-10-01
4
1,293 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

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

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

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

786 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