This week's book giveaway is in the Cloud/Virtualizaton forum.
We're giving away four copies of Mesos in Action and have Roger Ignazio on-line!
See this thread for details.
Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to replace apostophes?

 
James Hodgkiss
Ranch Hand
Posts: 401
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to replace all apostrophes in myString with \'

myString = myString.replace(''', '\''); doesn't work. What's the solution?

Cheers,
James
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15279
39
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The backslash is an escape character in Java string literals. If you want to have a literal backslash in a string literal, you must write \\ instead of \.

Note also that you cannot put more than one character between single quotes (a char literal is exactly one character).
 
James Hodgkiss
Ranch Hand
Posts: 401
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry Jesper, I wasn't very clear.

The code I want to use is:



but it has to be Java 1.1 compatible, so it must be two characters I pass to the replace method... Is there another solution?

Cheers,
James
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15279
39
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You cannot fit two characters: \' in a char literal, so you cannot use the replace() method that takes two chars.

If Java 1.1 doesn't have the replace() method that takes strings, then you'll have to program it yourself. Loop through the input string character by character, copy the characters to a StringBuffer, and when you encounter a ' in the input string, write \' to the StringBuffer. At the end call toString() on the StringBuffer to get the output string.
 
Michael Raymond Jr.
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by James Hodgkiss:
Sorry Jesper, I wasn't very clear.

The code I want to use is:



but it has to be Java 1.1 compatible, so it must be two characters I pass to the replace method... Is there another solution?

Cheers,
James



In 1.1 looks like you can use":
StringBuffer, int charAt() , and insert(int, char) to do the same thing as replace.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic