Results 1 to 2 of 2
  1. #1
    johnhelen is offline Member
    Join Date
    Feb 2011
    Posts
    4
    Rep Power
    0

    Default String.replace function

    Hello

    I want to replace two SubString inside a String.

    I tried the code below but it did not work

    Java Code:
    public String getFormattedString (String var1, String var2) {
        String rawText = "Name [name] and price [price]";
        rawText.replace("[name]", var1);
        rawText.replace ("[price]", var2);
        return rawText; 
    }
    If I changed to this, it will work but I believe this is not good way as I have to create 3 Strings

    Java Code:
    public String getFormattedString (String var1, String var2) {
        String rawText = "Name [name] and price [price]";
        String temp = rawText.replace("[name]", var1);
        String formattedText = temp.replace ("[price]", var2);
        return formattedText; 
    }
    Can you please help
    Many thanks
    john

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,234
    Rep Power
    19

    Default Re: String.replace function

    Strings are immutable. Every time you "change" a String you create a new String. Discarding the return values, as in your first code snippet, doesn't change that.

    Just do things the right way and stop worrying about possible micro-optimizations.

    db

Similar Threads

  1. String.replace ?!
    By HearT.Hunt3r in forum New To Java
    Replies: 4
    Last Post: 08-22-2011, 03:04 AM
  2. Replies: 1
    Last Post: 11-20-2010, 11:28 PM
  3. Replace String
    By Raeghin in forum New To Java
    Replies: 1
    Last Post: 07-28-2009, 03:58 PM
  4. string replace problem
    By soni in forum Advanced Java
    Replies: 8
    Last Post: 07-06-2008, 01:21 AM
  5. Find and replace ( in a String
    By hamish10101 in forum New To Java
    Replies: 6
    Last Post: 01-17-2008, 05:51 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •