StringBuffer method sampler
Since we already examined StringBuffer's constructor methods, we now examine the nonconstructor methods. For brevity, I focus on only 13 methods.
Note |
Like String, many StringBuffer methods require an index argument for accessing a character in the StringBuffer's value array (or a character array argument). That index/offset is always zero-based. |
- public StringBuffer append(char c) appends c's character to the contents of the current StringBuffer's value array and returns a reference to the current StringBuffer. Example: StringBuffer sb = new StringBuffer ("abc"); sb.append ('d'); System.out.println (sb); (output: abcd).
- public StringBuffer append(String str) appends the str-referenced String's characters to the contents of the current StringBuffer's value array and returns a reference to the current StringBuffer. Example: StringBuffer sb = new StringBuffer ("First,"); sb.append (" second"); System.out.println (sb); (output: First, second).
- public int capacity() returns the current StringBuffer's current capacity (that is, value's length). Example: StringBuffer sb = new StringBuffer (); System.out.println (sb.capacity ()); (output: 16).
- public char charAt(int index) extracts and returns the character at the index position in the current StringBuffer's value array. This method throws an IndexOutOfBoundsException object if index is negative, equals the string's length, or exceeds that length. Example: StringBuffer sb = new StringBuffer ("Test string"); for (int i = 0; i < sb.length (); i++) System.out.print (sb.charAt (i)); (output: Test string).
- public StringBuffer deleteCharAt(int index) removes the character at the index position in the current StringBuffer's value array. If index is negative, equals the string's length, or exceeds that length, this method throws a StringIndexOutOfBoundsException object. Example: StringBuffer sb = new StringBuffer ("abc"); sb.deleteCharAt (1); System.out.println (sb); (output: ac).
No comments:
Post a Comment