Results 1 to 6 of 6
Thread: How to use a StringBuffer?
- 02-17-2011, 09:04 PM #1
Member
- Join Date
- Feb 2011
- Posts
- 7
- Rep Power
- 0
How to use a StringBuffer?
So... I was trying to use this:
Is there any method available to insert a character at a specific position in a string?
For example:
st = "abde" <------ Original string
st= "abCde" <------ Add "C" in position 2
You can use StringBuffer to do this:
String st = new String("abcde");
st = StringBuffer(st).insert(2, "C").toString();
as an example for what I'm trying to do. Basically I just want to add a 1 or a 0 to the end of a pre-existing String. <-binary conversion stuff.
Anyway, so when i try to do it, Eclipse keeps telling me a I need to create a method for StringBuffer(String)..
example..
output = StringBuffer(output).insert("0").toString();
But it should be noted that I've already included: import java.lang.*;
in my code... Help?
Sorry if this seems dumb. I'm extremely new to java and coding in general.
-
The example I think forgot the word "new" in front of StringBuffer since you need to create a new StringBuffer object for this to work. Myself, I'd probably just use simple String concatenation unless you're doing this multiple times inside of a large or critical loop. If so, even then I'd not use a StringBuffer since it has extra unnecessary (in this case) overhead for thread-safety, and would use a StringBuilder object instead. You would use append(...) if adding to the end of the character sequence.
So for example
Java Code:output += "0"; // simple way output = [color="red"][b]new[/b][/color] StringBuilder(output).append("0").toString(); // if in a critical loop or a possible bottleneckLast edited by Fubarable; 02-17-2011 at 09:11 PM.
- 02-17-2011, 09:18 PM #3
Member
- Join Date
- Feb 2011
- Posts
- 7
- Rep Power
- 0
oh that was it. Thanks so much. =)
-
You're quite welcome.
Correction: if in a critical loop though, I'd create the StringBuilder object before the loop, append junk in inside the loop, and only call toString() on the StringBuilder after the loop.
- 02-18-2011, 05:24 AM #5
- 02-18-2011, 05:38 AM #6
Member
- Join Date
- Feb 2011
- Posts
- 7
- Rep Power
- 0
Similar Threads
-
How to do this with StringBuffer???
By mlibot in forum New To JavaReplies: 2Last Post: 03-24-2010, 12:40 AM -
java.lang.StringBuffer.append(StringBuffer.java(Co mpiled Code))
By Ashok Dave in forum Advanced JavaReplies: 3Last Post: 03-04-2009, 06:03 AM -
java.lang.StringBuffer.append(StringBuffer.java(Co mpiled Code))
By Ashok Dave in forum New To JavaReplies: 1Last Post: 03-03-2009, 05:27 AM -
StringBuffer
By Java Tip in forum Java TipReplies: 0Last Post: 11-08-2007, 08:33 AM -
Help with StringBuffer
By Marcus in forum AWT / SwingReplies: 2Last Post: 07-04-2007, 05:50 AM


LinkBack URL
About LinkBacks
Reply With Quote
.gif)

Bookmarks