[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

RE: Replace function (newbie help)



To further clarify the immutable String issue, note what you can do to a
String:

public class Main {
  /* purpose: remove the third character in the string */
  public static void main(String [] args) {
  String foo = "RTFM";
  foo = foo.substring(0,2) + foo.substring(3,4);
  System.out.println(foo);
  }
}

Note the output: RTM

Not that this is the most efficient approach, StringBuffer is your friend.
Try profiling some of these methods and see which is faster.

> -----Original Message-----
> From: Frank Merenda [mailto:fmerenda@atwork.com]
> Sent: Friday, October 05, 2001 12:21 PM
> To: ajug-members@www.ajug.org
> Subject: RE: Replace function (newbie help)
> 
> 
> All,
> 
> Just to make the immutable String issue clear to those that are new to
> Java, this method ( String replace() ) returns a new String 
> object that
> has replaced the old character with the new character. So it would be
> used like the following:
> 
> String myString = "Frank";
> String myNewString = myString.replace(.....);
> 
> This is considered inefficient code, because the replace function
> creates a new String object, thus creating two String Objects in this
> process.
> 
> Also, you can use the StringBuffer class to replace characters in the
> buffer as well. The string buffer can be used to append
> strings/characters/etc to it via the append() method, as well as other
> fun stuff like insert and delete characters and such. 
> 
> i.e.
> StringBuffer sb = new StringBuffer( "Frank" );
> sb.append( " is a geek" );
> sb.replace(...);
> String myString = sb.toString();
> 
> Hope that helps a little. :)
> Please excuse any typos in this, I'm just typing off the top of my
> head....
> 
> Thanks,
> Frank Merenda
> Senior Software Engineer
> AtWork Technologies, Inc.
> fmerenda@atwork.com 
> 
> > -----Original Message-----
> > From: Bhamani, Nizar [mailto:nizar.bhamani@proactcorp.com]
> > Sent: Friday, October 05, 2001 11:17 AM
> > To: 'monel.a.amin@mail.sprint.com'; ajug-members@www.ajug.org
> > Subject: RE: Replace function
> > 
> > 
> > You cannot modify a "String". You need to use "StringBuffer" 
> > to modify it.
> > 
> > use :
> > 
> > replace(int start, int end, String str) 
> > Replaces the characters in a substring of this StringBuffer 
> > with characters
> > in the specified String.
> > 
> > -----Original Message-----
> > From: monel.a.amin@mail.sprint.com 
> > [mailto:monel.a.amin@mail.sprint.com]
> > Sent: Friday, October 05, 2001 10:58 AM
> > To: ajug-members@www.ajug.org
> > Subject: Replace function
> > 
> > 
> > Hi All,
> > 
> > Is there an VB's Replace function's equivalent in Java?  I need to
> > replace a character in a String.
> > 
> > 
> > Any suggestions.....
> > 
> > Thanks,
> > Monel.
> > 
> > 
>