Thursday, April 4, 2013

The StringBuffer Class


Since String objects are immutable, you cannot manipulate the characters of an instantiated String. If you need to do this, use a java.lang.StringBuffer instead:


      // Create a string buffer from a string
      StringBuffer b = new StringBuffer("Mow");
      // Get and set individual characters of the StringBuffer
      char c1 = b.charAt(0); // Returns 'M': just like String.charAt()
      b.setCharAt(0, 'N'); // b holds "Now": can't do that with a String!
      // Append to a StringBuffer
      b.append(' '); // Append a character
      b.append("is the time."); // Append a string
      b.append(23); // Append an integer or any other value
      // Insert Strings or other values into a StringBuffer
      b.insert(6, "n't"); // b now holds: "Now isn't the time.23"
      // Replace a range of characters with a string (Java 1.2 and later)
      b.replace(4, 9, "is"); // Back to "Now is the time.23"
      // Delete characters
      b.delete(16, 18); // Delete a range: "Now is the time"
      b.deleteCharAt(2); // Delete 2nd character: "No is the time"
      b.setLength(5); // Truncate by setting the length: "No is"
      // Other useful operations
      b.reverse(); // Reverse characters: "si oN"
      String s11 = b.toString(); // Convert back to an immutable string
      s11 = b.substring(1,2); // Or take a substring: "i"
      b.setLength(0); // Erase buffer; now it is ready for reuse

No comments:

Post a Comment