This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Java in General and the fly likes How to replace apostophes? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "How to replace apostophes?" Watch "How to replace apostophes?" New topic
Author

How to replace apostophes?

James Hodgkiss
Ranch Hand

Joined: Jan 22, 2004
Posts: 401
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

Joined: Aug 16, 2005
Posts: 14278
    
  21

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).


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
James Hodgkiss
Ranch Hand

Joined: Jan 22, 2004
Posts: 401
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

Joined: Aug 16, 2005
Posts: 14278
    
  21

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

Joined: May 16, 2005
Posts: 178
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.


Scooby Snacks for everyone...<br /> <br />SCJA, SCJP 1.4
 
 
subject: How to replace apostophes?