Java Reference
In-Depth Information
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 implementa-
tions 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 re-
turns 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;
}