• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Char Conversion

 
Celinio Fernandes
Ranch Hand
Posts: 549
Eclipse IDE Google Web Toolkit Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
how do you replace a simple quote with a backslash followed by a simple quote ?

That is I want to replace ' with \'





Thanks
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
\ is a special character in Java Strings so you need to escape it.
 
Celinio Fernandes
Ranch Hand
Posts: 549
Eclipse IDE Google Web Toolkit Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I actually need 4 backslahes !



Thanks anyway.
 
Henry Wong
author
Marshal
Pie
Posts: 20881
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Thavanathan Thangaraj
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
myString.replace('\'', '\\');
 
Campbell Ritchie
Sheriff
Posts: 48370
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 378
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually that will replace ' with '
So you are back to square one..
 
Gamini Sirisena
Ranch Hand
Posts: 378
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 378
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic