wood burning stoves
The moose likes Beginning Java and the fly likes String replacement Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String replacement" Watch "String replacement" New topic

String replacement

Amirtharaj Chinnaraj
Ranch Hand

Joined: Sep 28, 2006
Posts: 241
hey guys

i want change the sting value test's to test\'s
stored in a string

this the code i tried but the result is not getting changed i want to know
why it is not changed and how i can change

String test="test's";
test= test.replace("'", "'/");
String test1 =test;

Ronda Spring

Joined: Feb 15, 2007
Posts: 1
Strings are immutable - mostly for safety/security reasons that are beyond me. Once made their contents are not altered. The replace() method is returning the altered string, but it needs a new home.

String s = "test";
String x = s.replace("s", "x");

This turns test to text, but you won't see the result in s, only in x.
Joanne Neal

Joined: Aug 05, 2005
Posts: 3742
You say in your question that you want to chage test's to test\'s, but your code is trying to change it to test'/s

Assuming you wanted what you said in the question, you need to escape the '\', because '\' is a special character in Java Strings.

@Ronda - this will work because test is a String reference, so the second line actually just points it at the new String and the original String is no longer referenced and so is available for garbage collection.

With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
subject: String replacement
It's not a secret anymore!