aspose file tools*
The moose likes Beginning Java and the fly likes Char Conversion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Char Conversion" Watch "Char Conversion" New topic
Author

Char Conversion

Celinio Fernandes
Ranch Hand

Joined: Jun 28, 2003
Posts: 548

Hi,
how do you replace a simple quote with a backslash followed by a simple quote ?

That is I want to replace ' with \'





Thanks


SCJP 1.4, SCWCD 1.4, SCBCD 1.3, SCBCD 5
Visit my blog
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3742
    
  16
\ is a special character in Java Strings so you need to escape it.


Joanne
Celinio Fernandes
Ranch Hand

Joined: Jun 28, 2003
Posts: 548

I actually need 4 backslahes !



Thanks anyway.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 19063
    
  40

Originally posted by Celinio Fernandes:
I actually need 4 backslahes !

Thanks anyway.


The reason that you need four backslashes is because the backslash has special meaning in a regex replacement string. And as mentioned, the backslash has special mean in a Java string literal.

So, to have one literal backslash, you need to escape the backslash with a backslash to turn off the regex replacement string meaning. Then you must escape the two backslashes, each with a backslash to turn off the special meaning in the Java string literal..... hance, 4 backslashes.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Thavanathan Thangaraj
Greenhorn

Joined: Jul 27, 2008
Posts: 1
myString.replace('\'', '\\');
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40052
    
  28
Originally posted by Thavanathan Thangaraj:
myString.replace('\'', '\\');
Welcome to JavaRanch

I am afraid that suggestion will simply replace all ' marks with \, so it won't do what Celinio wanted.
Gamini Sirisena
Ranch Hand

Joined: Aug 05, 2008
Posts: 378
Actually that will replace ' with '
So you are back to square one..
Gamini Sirisena
Ranch Hand

Joined: Aug 05, 2008
Posts: 378
Seems I am wrong...
for "java'ranch".replace("\","\\'");
the result seems to be...


\'j\'a\'v\'a\''\'r\'a\'n\'c\'h\'
Gamini Sirisena
Ranch Hand

Joined: Aug 05, 2008
Posts: 378
Looks like I am wrong again and Campbell was right..

"java'ranch".replace("\'", "\\"); Got the arguments wrong..

gives..

java\ranch

sorry guys for the mess...
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Char Conversion