Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

StringBuffer length and how to edit the data 1

Status
Not open for further replies.

Enea

Technical User
Feb 23, 2005
90
US
I am learning about StringBuffer and have two questions:
[1] I tried creating a new String using StringBuffer, initialize it and specify it's length using the following statement:

StringBuffer s=new StringBuffer("Hi Gisela".length());

However when I do System.out.println(s); it does not display anything. Why? Where did "HI Gïsela" go?

[2] I understand that StringBuffer allows the program to edit its contents.
If I have StringBuffer s1=new SringBuffer("Hello");
how do I change the String to "Bye"?




 
Code:
StringBuffer s=new StringBuffer("Hi Gisela".length());

This uses a constructor of StringBuffer which tells it reserve the given space, rather than the content. You want

Code:
StringBuffer s=new StringBuffer("Hi Gisela");

... to assign the content instead.

To change the content as you asked ...
Code:
StringBuffer s1=new StringBuffer("Hello");
s1.replace(0,5, "bye");

...although in this case, because you're replacing the whole content, you could simply clear the contents and re-assign them
Code:
StringBuffer s1=new StringBuffer("Hello");
s1.clear();
s1.append("bye");

Use the Java API docs. You would find all this there.


Tim
 
Thank you Tim for your clear answer. I now understand.
Thank you very much,
Enea
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top