The String and StringBuffer Classes |
Theclass ReverseString { public static String reverseIt(String source) { int i, len = source.length(); StringBuffer dest = new StringBuffer(len); for (i = (len - 1); i >= 0; i--) { dest.append(source.charAt(i)); } return dest.toString(); } }reverseIt()
method uses StringBuffer'sappend()
method to add a character to the end of the destination string:dest
. If the appended character causes the size of the StringBuffer to grow beyond its current capacity, the StringBuffer allocates more memory. Because memory allocation is a relatively expensive operation, you can make your code more efficient by initializing a StringBuffer's capacity to a reasonable first guess, thereby minimizing the number of times memory must be allocated for it. For example, thereverseIt()
method constructs the StringBuffer with an initial capacity equal to the length of the source string, ensuring only one memory allocation fordest
.The version of the
append()
method used inreverseIt()
is only one of the StringBuffer methods that appends data to the end of a StringBuffer. There are severalappend()
methods that append data of various types, such asfloat
,int
,boolean
, and even Object, to the end of the StringBuffer. The data is converted to a string before the append operation takes place.Inserting Characters
At times, you may want to insert data into the middle of a StringBuffer. You do this with one of StringBufffer'sinsert()
methods. This example illustrates how you would insert a string into a StringBuffer:This code snippet prints:StringBuffer sb = new StringBuffer("Drink Java!"); sb.insert(6, "Hot "); System.out.println(sb.toString());With StringBuffer's manyDrink Hot Java!insert()
methods, you specify the index before which you want the data inserted. In the example, "Hot " needed to be inserted before the 'J' in "Java". Indices begin at 0, so the index for 'J' is 6. To insert data at the beginning of a StringBuffer, use an index of 0. To add data at the end of a StringBuffer, use an index equal to the current length of the StringBuffer or useappend()
.Setting Characters
Another useful StringBuffer modifier issetCharAt()
, which sets the character at a specific location in the StringBuffer.setCharAt()
is useful when you want to reuse a StringBuffer.
The String and StringBuffer Classes |