|
|
The String and StringBuffer Classes |
StringBuffers
ThereverseItmethod usesStringBuffer'sappendmethod to add a character to the end of the destination string:dest.If the appended character causes the size of 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(); } }StringBufferto grow beyond its current capacity, theStringBufferallocates more memory. Because memory allocation is a relatively expensive operation, you can make your code more efficient by initializing aStringBuffer's capacity to a reasonable first guess, thereby minimizing the number of times memory must be allocated for it. For example, thereverseItmethod constructs theStringBufferwith an initial capacity equal to the length of the source string, ensuring only one memory allocation fordest.The version of the
appendmethod used inreverseItis only one of theStringBuffermethods that appends data to the end of aStringBuffer. There are severalappendmethods that append data of various types, such asfloat,int,boolean, and evenObject, to the end of theStringBuffer. 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 aStringBuffer. You do this with one of StringBufffer'sinsertmethods. This example illustrates how you would insert a string into aStringBuffer:This code snippet prints:StringBuffer sb = new StringBuffer("Drink Java!"); sb.insert(6, "Hot "); System.out.println(sb.toString());WithDrink Hot Java!StringBuffer's manyinsertmethods, 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 aStringBuffer, use an index of 0. To add data at the end of aStringBuffer, use an index equal to the current length of theStringBufferor useappend.Setting Characters
Another usefulStringBuffermodifier issetCharAt, which replaces the character at a specific location in theStringBufferwith the character specified in the argument list..setCharAtis useful when you want to reuse aStringBuffer.
|
|
The String and StringBuffer Classes |