Thursday 16 March 2017

String Methods Added by Java 2, Version 1.4 & StringBuffer - Java Tutorials

String Methods Added by Java 2, Version 1.4

Java 2, version 1.4 adds several methods to the String class. These are summarized in the following table.


boolean contentEquals(StringBuffer str):   Returns true if the invoking string contains the same string as str. Otherwise, returns false.

CharSequence, subSequence (int startIndex, int stopIndex): Returns a substring of the invoking string, beginning at startIndex and stopping at stopIndex. This method is required by the CharSequence interface, which is now implemented by String.

boolean matches(string regExp):  Returns true if the invoking string matches the regular expression passed in regExp. Otherwise, returns false.

String  replaceFirst(String regExp, String newStr):   Returns a string in which the first substring that matches the regular expression specified by regExp is replaced by newStr.

String replaceAll(String regExp, String newStr):   Returns a string in which all substrings that match the regular expression specified by regExp are replaced by newStr.

String[ ] split(String regExp):   Decomposes the invoking string into parts and returns an array that contains the result. Each part is delimited by the regular expression passed in regExp.

String[ ] split(String regExp, int max):   Decomposes the invoking string into parts and returns an array that contains the result. Each part is delimited by the regular expression passed in regExp. The number of pieces is specified by max. If max is negative, then the invoking string is fully decomposed. Otherwise, if max contains a non-zero value, the last entry in the returned array contains the remainder of the invoking string. If max is zero, the invoking string is fully decomposed.

Notice that several of these methods work with regular expressions. Support for regular expression processing was added by Java 2, version 1.4 and is described in Chapter 24.




StringBuffer

StringBuffer is a peer class of String that provides much of the functionality of strings. As you know, String represents fixed-length, immutable character sequences. In contrast, StringBuffer represents growable and writeable character sequences. StringBuffer may have characters and substrings inserted in the middle or appended to the end. StringBuffer will automatically grow to make room for such additions and often has more characters preallocated than are actually needed, to allow room for growth. Java uses both classes heavily, but many programmers deal only with String and let Java manipulate StringBuffers behind the scenes by using the overloaded + operator.


StringBuffer Constructors

StringBuffer defines these three constructors:

      StringBuffer( )
      StringBuffer(int size)
      StringBuffer(String str)

The default constructor (the one with no parameters) reserves room for 16 characters without reallocation. The second version accepts an integer argument that explicitly sets the size of the buffer. The third version accepts a String argument that sets the initial contents of the StringBuffer object and reserves room for 16 more characters without reallocation. StringBuffer allocates room for 16 additional characters when no specific buffer length is requested, because reallocation is a costly process in terms of time. Also, frequent reallocations can fragment memory. By allocating room for a few extra characters, StringBuffer reduces the number of reallocations that take place.


length( ) and capacity( )

The current length of a StringBuffer can be found via the length( ) method, while the total allocated capacity can be found through the capacity( ) method. They have the following general forms:

      int length( )
      int capacity( )

Here is an example:

  // StringBuffer length vs. capacity.
  class StringBufferDemo {
    public static void main(String args[]) {
      StringBuffer sb = new StringBuffer("Hello");

      System.out.println("buffer = " + sb);
      System.out.println("length = " + sb.length());
      System.out.println("capacity = " + sb.capacity());
    }
  }

Here is the output of this program, which shows how StringBuffer reserves extra space for additional manipulations:

  buffer = Hello
  length = 5
  capacity = 21

Since sb is initialized with the string “Hello” when it is created, its length is 5. Its capacity is 21 because room for 16 additional characters is automatically added.


ensureCapacity( )

If you want to preallocate room for a certain number of characters after a StringBuffer has been constructed, you can use ensureCapacity( ) to set the size of the buffer. This is useful if you know in advance that you will be appending a large number of small strings to a StringBuffer. ensureCapacity ( ) has this general form:

      void ensureCapacity(int capacity)

      Here, capacity specifies the size of the buffer.


setLength( )

To set the length of the buffer within a StringBuffer object, use setLength( ). Its general form is shown here:

      void setLength(int len)

Here, len specifies the length of the buffer. This value must be nonnegative. When you increase the size of the buffer, null characters are added to the end of the existing buffer. If you call setLength( ) with a value less than the current value returned by length( ), then the characters stored beyond the new length will be lost. The setCharAtDemo sample program in the following section uses setLength( ) to shorten a StringBuffer.


charAt( ) and setCharAt( )

The value of a single character can be obtained from a StringBuffer via the charAt( ) method. You can set the value of a character within a StringBuffer using setCharAt( ). Their general forms are shown here:

      char charAt(int where)
      void setCharAt(int where, char ch)

For charAt( ), where specifies the index of the character being obtained. For setCharAt( ), where specifies the index of the character being set, and ch specifies the new value of that character. For both methods, where must be nonnegative and must not specify a location beyond the end of the buffer.

The following example demonstrates charAt( ) and setCharAt( ):

  // Demonstrate charAt() and setCharAt().
  class setCharAtDemo {
    public static void main(String args[]) {
      StringBuffer sb = new StringBuffer("Hello");
      System.out.println("buffer before = " + sb);
      System.out.println("charAt(1) before = " + sb.charAt(1));
        sb.setCharAt(1, 'i');
        sb.setLength(2);
        System.out.println("buffer after = " + sb);
        System.out.println("charAt(1) after = " + sb.charAt(1));
    }
  }

Here is the output generated by this program:

  buffer before = Hello
  charAt(1) before = e
  buffer after = Hi
  charAt(1) after = i


getChars( )

To copy a substring of a StringBuffer into an array, use the getChars( ) method. It has this general form:

      void getChars(int sourceStart, int sourceEnd, char target[ ],
                              int targetStart)

Here, sourceStart specifies the index of the beginning of the substring, and sourceEnd specifies an index that is one past the end of the desired substring. This means that the substring contains the characters from sourceStart through sourceEnd–1. The array that will receive the characters is specified by target. The index within target at which the substring will be copied is passed in targetStart. Care must be taken to assure that the target array is large enough to hold the number of characters in the specified substring.


append( )

The append( ) method concatenates the string representation of any other type of data to the end of the invoking StringBuffer object. It has overloaded versions for all the built-in types and for Object. Here are a few of its forms:

      StringBuffer append(String str)
      StringBuffer append(int num)
      StringBuffer append(Object obj)

String.valueOf( ) is called for each parameter to obtain its string representation. The result is appended to the current StringBuffer object. The buffer itself is returned by each version of append( ). This allows subsequent calls to be chained together, as shown in the following example:

  // Demonstrate append().
  class appendDemo {
    public static void main(String args[]) {
      String s;
      int a = 42;
      StringBuffer sb = new StringBuffer(40);

      s = sb.append("a = ").append(a).append("!").toString();
      System.out.println(s);
    }
  }

The output of this example is shown here:

  a = 42!

The append( ) method is most often called when the + operator is used on String objects. Java automatically changes modifications to a String instance into similar operations on a StringBuffer instance. Thus, a concatenation invokes append( ) on a StringBuffer object. After the concatenation has been performed, the compiler inserts a call to toString( ) to turn the modifiable StringBuffer back into a constant String. All of this may seem unreasonably complicated. Why not just have one string class and have it behave more or less like StringBuffer? The answer is performance. There are many optimizations that the Java run time can make knowing that String objects are immutable. Thankfully, Java hides most of the complexity of conversion between Strings and StringBuffers. Actually, many programmers will never feel the need to use StringBuffer directly and will be able to express most operations in terms of the + operator on String variables.


insert( )

The insert( ) method inserts one string into another. It is overloaded to accept values of all the simple types, plus Strings and Objects. Like append( ), it calls String.valueOf( ) to obtain the string representation of the value it is called with. This string is the inserted into the invoking StringBuffer object. These are a few of its forms:

      StringBuffer insert(int index, String str)
      StringBuffer insert(int index, char ch)
      StringBuffer insert(int index, Object obj)

Here, index specifies the index at which point the string will be inserted into the invoking StringBuffer object. The following sample program inserts “like” between “I” and “Java”:

  // Demonstrate insert().
  class insertDemo {
    public static void main(String args[]) {
      StringBuffer sb = new StringBuffer("I Java!");

      sb.insert(2, "like ");
      System.out.println(sb);
    }
  }

The output of this example is shown here:

  I like Java!


reverse( )

You can reverse the characters within a StringBuffer object using reverse( ), shown here:

      StringBuffer reverse( )

This method returns the reversed object on which it was called. The following program demonstrates reverse( ):

  // Using reverse() to reverse a StringBuffer.
  class ReverseDemo {
    public static void main(String args[]) {
      StringBuffer s = new StringBuffer("abcdef");

      System.out.println(s);
      s.reverse();
      System.out.println(s);
    }
  }

Here is the output produced by the program:

  abcdef
  fedcba


delete( ) and deleteCharAt( )

Java 2 added to StringBuffer the ability to delete characters using the methods delete( ) and deleteCharAt( ). These methods are shown here:

      StringBuffer delete(int startIndex, int endIndex)
      StringBuffer deleteCharAt(int loc)

The delete( ) method deletes a sequence of characters from the invoking object. Here, startIndex specifies the index of the first character to remove, and endIndex specifies an index one past the last character to remove. Thus, the substring deleted runs from startIndex to endIndex–1. The resulting StringBuffer object is returned.

The deleteCharAt( ) method deletes the character at the index specified by loc. It returns the resulting StringBuffer object.

Here is a program that demonstrates the delete( ) and deleteCharAt( ) methods:

  // Demonstrate delete() and deleteCharAt()
  class deleteDemo {
    public static void main(String args[]) {
      StringBuffer sb = new StringBuffer("This is a test.");

      sb.delete(4, 7);
      System.out.println("After delete: " + sb);

      sb.deleteCharAt(0);
      System.out.println("After deleteCharAt: " + sb);
    }
  } 

The following output is produced:

  After delete: This a test.
  After deleteCharAt: his a test.


replace( )

Another method added to StringBuffer by Java 2 is replace( ). It replaces one set of characters with another set inside a StringBuffer object. Its signature is shown here:

      StringBuffer replace(int startIndex, int endIndex, String str)

The substring being replaced is specified by the indexes startIndex and endIndex. Thus, the substring at startIndex through endIndex–1 is replaced. The replacement string is passed in str. The resulting StringBuffer object is returned.

The following program demonstrates replace( ):

  // Demonstrate replace()
  class replaceDemo {
    public static void main(String args[]) {
      StringBuffer sb = new StringBuffer("This is a test.");

      sb.replace(5, 7, "was");
      System.out.println("After replace: " + sb);
    }
  }

Here is the output:

  After replace: This was a test.


substring( )

Java 2 also added the substring( ) method, which returns a portion of a StringBuffer. It has the following two forms:

      String substring(int startIndex)
      String substring(int startIndex, int endIndex)

The first form returns the substring that starts at startIndex and runs to the end of the invoking StringBuffer object. The second form returns the substring that starts at startIndex and runs through endIndex–1. These methods work just like those defined for String that were described earlier.


StringBuffer Methods Added by Java 2, Version 1.4

Java 2, version 1.4 added several new methods to StringBuffer. They are summarized in the following table.


CharSequence subSequence(int startIndex,  int stopIndex): Returns a substring of the invoking string, beginning at startIndex and stopping at stopIndex. This method is required by the CharSequence interface, which is now implemented by StringBuffer.

int indexOf(String str):  Searches the invoking StringBuffer for the first occurrence of str. Returns the index of the match, or –1 if no match is found.

int indexOf(String str, int startIndex):  Searches the invoking StringBuffer for the first occurrence of str, beginning at startIndex. Returns the index of the match, or –1 if no match is found.

int lastIndexOf(String str):   Searches the invoking StringBuffer for the last occurrence of str. Returns the index of the match, or –1 if no match is found.

int lastIndexOf(String str, int startIndex):   Searches the invoking StringBuffer for the last occurrence of str, beginning at startIndex. Returns the index of the match, or –1 if no match is found.


Aside from subSequence( ), which implements a method required by the CharSequence interface, the other methods allow a StringBuffer to be searched for an occurrence of a String. The following program demonstrates indexOf( ) and lastIndexOf( ).

  class IndexOfDemo {
    public static void main(String args[]) {
      StringBuffer sb = new StringBuffer("one two one");
      int i;

      i = sb.indexOf("one");
      System.out.println("First index: " + i);

      i = sb.lastIndexOf("one");
      System.out.println("Last index: " + i);
    }
  }

The output is shown here.

  First index: 0
  Last index: 8

No comments:

Post a Comment