• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

String replacement

 
Ranch Hand
Posts: 242
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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;

regards
amir
 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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");
System.out.println(s);
System.out.println(x);

This turns test to text, but you won't see the result in s, only in x.
 
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
Try

@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.
 
What's a year in metric? Do you know this metric stuff tiny ad?
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic