Re: Converting char(s) into String



John O'Conner wrote:
ponga wrote:
String str = "" + s1.charAt(0) + s1.charAt(5);

Maybe a less confusing way to do this is this:

StringBuffer strBuf = new StringBuffer();
strBuff.append(s1.charAt(0));
strBuff.append(s1.charAt(5));
String str = strBuff.toString();

One thing to be aware of is that passing a char to the constructor does not do what you may expect.

String str =
new StringBuilder(s1.charAt(0)).append(s2.charAt(5)).toString();

You don't need to go through StringBuffer (or better StringBuilder) for something this simple.

String str = String.valueOf(new char[] { s1.charAt(0), s1.charAt(5) });

Tom Hawtin
--
Unemployed English Java programmer
http://jroller.com/page/tackline/
.



Relevant Pages

  • Re: Getting rid of double spacing
    ... >using the tokenizer method? ... I was thinking of doing a loop that goes on ... How do I delete a char? ... create a stringbuffer with just the chars you want. ...
    (comp.lang.java.help)
  • a simple question realted to StringBuffer
    ... I am using a StringBuffer to hold a line with fixed length of 72 chars. ... Later, I am going to put char at a specified location, using setCharAtmethod. ...
    (comp.lang.java.programmer)
  • Re: StringBuffer/StringBuilder efficiency
    ... The JDK documentation doesn't promise a particular implementation, but in reality, it's basically the same thing StringBuffer and StringBuilder do: allocate new storage, copy the existing data over. ... char[] array fills it's added to an ArrayList of chararrays. ... That will need growing much less frequently, and at the end a single right-size chararray is allocated to copy everything into. ...
    (comp.lang.java.programmer)
  • Re: a simple question realted to StringBuffer
    ... I am using a StringBuffer to hold a line with fixed length of 72 chars. ... Later, I am going to put char at a specified location, using setCharAtmethod. ... Since the same loop is going on in the background, maybe it doesn't matter which of the above you use. ...
    (comp.lang.java.programmer)
  • Re: String Theory
    ... > Of course it would be clever to use a StringBuffer in that case or ... > explicitely copy the part of the charfrom the orig String... ... or new String) which does create a small char ...
    (comp.lang.java.programmer)