Java Reference
In-Depth Information
}
}
System
.
out
.
println
(
sb2
);
The first method uses the
StringBuilder.length()
method, so it will only work correctly
when you are starting with an empty
StringBuilder
. The second method relies on calling
the informational method
hasMoreElements()
in the
Enumeration
(or
hasNext()
in an
Iterator
, as discussed in
Using Iterators or Enumerations for Data-Independent Access
)
more than once on each element. An alternative method, particularly when you aren't start-
ing with an empty builder, would be to use a
boolean
flag variable to track whether you're at
the beginning of the list.
Processing a String One Character at a Time
Problem
You want to process the contents of a string, one character at a time.
Solution
Use a
for
loop and the
String
's
charAt()
method. Or a “for each” loop and the
String
's
toCharArray
method.
Discussion
A string's
charAt()
method retrieves a given character by index number (starting at zero)
from within the
String
object. To process all the characters in a
String
, one after another,
use a
for
loop ranging from zero to
String.length()-1
. Here we process all the characters
in a
String
:
strings/StrCharAt.java
public
public class
class
StrCharAt
StrCharAt
{
public
public static
void
main
(
String
[]
av
) {
String a
=
"A quick bronze fox lept a lazy bovine"
;
for
static
void
for
(
int
int
i
=
0
;
i
<
a
.
length
();
i
++)
// Don't use foreach
System
.
out
.
println
(
"Char "
+
i
+
" is "
+
a
.
charAt
(
i
));