This week's giveaway is in the EJB and other Java EE Technologies forum.
We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan 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 EJB 3 in Action this week in the EJB and other Java EE Technologies 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: 13870
    
  10

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 7 API documentation
Scala Notes - My blog about Scala
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: 13870
    
  10

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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to replace apostophes?
 
Similar Threads
Int to String
how to check whether a string is null or not
how to replace eol and nl
determine the input type of the value of the function parameter map
problems with replaceAll and slash character