THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1
Constructs a new String with the same contents as the given
StringBuilder.

publicString(StringBuffer value)

Constructs a new String with the same contents as the given
StringBuffer.

The most basic methods of String objects are length and charAt, as defined by the CharSequence
interface. This loop counts the number of each kind of character in a string:


for (int i = 0; i < str.length(); i++)
counts[str.charAt(i)]++;


Note that length is a method for String, while for array it is a fieldit's common for beginners to confuse
the two.


In most String methods, a string index position less than zero or greater than length()-1 throws an
IndexOutOfBoundsException. Some implementations throw the more specific
StringIndexOutOfBoundsException, which can take the illegal index as a constructor argument and
then include it in a detailed message. Methods or constructors that copy values to or from an array will also
throw IndexOutOfBoundsException if any attempt is made to access outside the bounds of that array.


There are also simple methods to find the first or last occurrence of a particular character or substring in a
string. The following method returns the number of characters between the first and last occurrences of a
given character in a string:


static int countBetween(String str, char ch) {
int begPos = str.indexOf(ch);
if (begPos < 0) // not there
return -1;
int endPos = str.lastIndexOf(ch);
return endPos - begPos - 1;
}


The countBetween method finds the first and last positions of the character ch in the string str. If the
character does not occur twice in the string, the method returns -1. The difference between the two character
positions is one more than the number of characters in between (if the two positions were 2 and 3, the number
of characters in between is zero).


Several overloads of the method indexOf search forward in a string, and several overloads of
lastIndexOf search backward. Each method returns the index of what it found, or 1 if the search was
unsuccessful:


Method Returns Index Of...

indexOf(int ch) first position of ch

indexOf(int ch, int start) first position of ch start

indexOf(String str) first position of str

indexOf(String str, int start) first position of str start
Free download pdf