Chapter 10 Strings and Characters 563 the characters

Chapter 10 Strings and Characters 563 the characters are truncated to the specified length (i.e., the characters in the String- Bufferafter the specified length are discarded). If the specified length is greater than the number of characters currently in the StringBuffer, null characters (characters with the numeric representation 0) are appended to the StringBufferuntil the total number of characters in the StringBuffer is equal to the specified length. 10.16 StringBufferMethods charAt, setCharAt, getCharsand reverse Class StringBufferprovides the charAt, setCharAt, getChars and reverse methods to manipulate the characters in a StringBuffer. Method charAttakes an integer argument and returns the character in the StringBuffer at that index. Method setCharAttakes an integer and a character argument and sets the character at the specified position to the character argument. The index specified in the charAt and set- CharAt methods must be greater than or equal to 0 and less than the StringBuffer length; otherwise, a StringIndexOutOfBoundsExceptionis generated. Common Programming Error 10.5 Attempting to access a character that is outside the bounds of a StringBuffer (i.e., an index less than 0 or an index greater than or equal to the StringBuffer s length) results in a StringIndexOutOfBoundsException. Method getCharsreturns a character array containing a copy of the characters in the StringBuffer. This method takes four arguments the starting index from which characters should be copied in the StringBuffer, the index one past the last character to be copied from the StringBuffer, the character array into which the characters are to be copied and the starting location in the character array where the first character should be placed. Method reverse reverses the contents of the StringBuffer. Each of these methods is demonstrated in Fig. 10.14. 1 // Fig. 10.14: StringBufferChars.java 2 // The charAt, setCharAt, getChars, and reverse methods 3 // of class StringBuffer. 4 5 // Java extension packages 6 import javax.swing.*; 7 8 public class StringBufferChars { 9 10 // test StringBuffer character methods 11 public static void main( String args[] ) 12 { 13 StringBuffer buffer = new StringBuffer( “hello there” ); 14 15 String output = “buffer = ” + buffer.toString() + 16 “nCharacter at 0: ” + buffer.charAt( 0 ) + 17 “nCharacter at 4: ” + buffer.charAt( 4 ); 18 Fig. 10.14 StringBufferclass character manipulation methods. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Leave a Reply