Java Reference
In-Depth Information
Lower: java cookbook
equals( ) correctly reports false
equalsIgnoreCase( ) correctly reports true
See Also
Regular expressions make it simpler to ignore case in string searching (see Chapter 4 ) .
Indenting Text Documents
Problem
You need to indent (or “undent” or “dedent”) a text document.
Solution
To indent, either generate a fixed-length string and prepend it to each output line, or use a
for loop and print the right number of spaces:
while
while (( inputLine = is . readLine ()) != null
null ) {
for
for ( int
int i = 0 ; i < nSpaces ; i ++) System . out . print ( ' ' );
System . out . println ( inputLine );
}
A more efficient approach to generating the spaces might be to construct a long string of
spaces and use substring() to get the number of spaces you need.
To undent, use substring to generate a string that does not include the leading spaces. Be
careful of inputs that are shorter than the amount you are removing! By popular demand, I'll
give you this one, too. First, though, here's a demonstration of an Undent object created with
an undent value of 5, meaning remove up to five spaces (but don't lose other characters in
the first five positions):
$ java strings.Undent
Hello World
Hello World
Hello
Hello
Search WWH ::




Custom Search