2.8. Creating an Emphasized Header
Problem
You would like to print an attention-grabbing header.
Solution
Combine the powers of StringUtils.repeat()
, StringUtils.center( ),
and StringUtils.join( ) to create a textual
header. The following example demonstrates the use of these three
methods to create a header:
public String createHeader( String title ) {
int width = 30;
// Construct heading using StringUtils: repeat( ), center( ), and join( )
String stars = StringUtils.repeat( "*", width);
String centered = StringUtils.center( title, width, "*" );
String heading =
StringUtils.join(new Object[]{stars, centered, stars}, "\n");
return heading;
}Here’s the output of
createHeader("TEST"):
****************************** ************ TEST ************ ******************************
Discussion
In the example, StringUtils.repeat( ) creates the
top and bottom rows with StringUtils.repeat("*", 30), creating a string with 30 consecutive
* characters. Calling
StringUtils.center(title, width, "*") creates a
middle line with the header title centered and surrounded by
* characters. StringUtils.join() joins the lines together with the newline characters, and
out pops a header.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access