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.
Get Jakarta Commons Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.