Java Reference
In-Depth Information
}
iif
(
match
.
length
() ==
0
) {
match
=
""
;
}
list
.
add
(
match
);
}
return
return
list
;
}
}
It is sometimes “downright scary” how much mundane code you can eliminate with a single,
well-formulated regular expression.
Program: A Simple Text Formatter
This program is a very primitive text formatter, representative of what people used on most
computing platforms before the rise of standalone graphics-based word processors, laser
printers, and, eventually, desktop publishing and desktop office suites. It simply reads words
from a file—previously created with a text editor—and outputs them until it reaches the right
margin, when it calls
println()
to append a line ending. For example, here is an input file:
It's a nice
day, isn't it, Mr. Mxyzzptllxy?
I think we should
go for a walk.
Given the preceding as its input, the
Fmt
program prints the lines formatted neatly:
It's a nice day, isn't it, Mr. Mxyzzptllxy? I think we should go for a
walk.
As you can see, it fits the text we gave it to the margin and discards all the line breaks
present in the original. Here's the code:
public
public class
Fmt
{
/** The maximum column width */
public
class
Fmt
public static
int
COLWIDTH
=
72
;
/** The file that we read and format */
final
static final
final
int
final
BufferedReader in
;