• Post Reply Bookmark Topic Watch Topic
  • New Topic

replace method for String  RSS feed

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have the following String:
Bob's house
and need to change it to:
Bob''s house
I tried using the replace method for String:
public class Replacetest
{
public static void main(String args[])
{

String str="bob's";
System.out.println(str);
String mystr;
mystr = str.replace('\'','\'\'');
System.out.println(mystr);
}
}
However, I'm getting an errors trying to do this. Does anyone have any suggestions that would help?
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Bob's".replace('\'', '\"') results in the string Bob"s
Or is that Bob''s with two single quotes?
[ April 18, 2003: Message edited by: Barry Gaunt ]
 
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String.replace takes two chars a parameters, not two Strings.
--or, As I re-read your post, I note that you are trying to push two single quotes in as one character?
Try this:

Note that you don't need to escape the single quote (')--but it doesn't hurt if you do.
There's also a replaceFirst method if you want that instead of replaceAll.
Be aware that the first string parameter to replaceAll and replaceFirst is a regular expression string. This is fine for alpha-numberic replacements; however, if you want to use other characters, I suggest making yourself familiar with regular expressions if you are not already so.
[ April 18, 2003: Message edited by: Joel McNary ]
 
mark babcock
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I cannot escape to a double quote it must be two single quotes. when I try to escape to
string.replace('\'', '\''');
I get an error because it must be two single quotes..
 
mark babcock
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Joel,
That did the trick!
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!