Java Reference
In-Depth Information
This is an empty
StringBuffer
object ready to receive the revised text. We can now search for and
replace instances of "
dog
" in
joke
by calling the
find()
method for
m
, and calling
appendReplacement()
each time it returns
true
:
while(m.find())
m.appendReplacement(newJoke, "goat");
Each call of
appendReplacement()
copies characters from
joke
to
newJoke
starting at the
character where the previous
find()
operation started and ending at the character preceding the first
character matched: at
m.start()-1
in other words. The method will then append the string specified
by the second argument to
newJoke
. This process is illustrated below.
Search start
joke
My dog hasn't got any nose.
How does your dog smell then?
My dog smells horrible.
append Replacement
Replacement
new joke
My goat
Search start
joke
My dog hasn't got any nose.
How does your dog smell then?
My dog smells horrible.
append Replacement
Replacement
new joke
My goat hasn't got any nose.
Replacement
How does your goat
goat
joke
My dog hasn't got any nose.
Search start
How does your dog smell then?
My dog smells horrible.
append Replacement
new joke
My goat hasn't got any nose.
How does your goat
goat
Replacement
My goat