tnichol
tnichol

Reputation: 155

Formatting string output in groovy

I'm trying to print out a basic header in Groovy. I need the first line to have the date left-justified, with the name of the institution centered, and page number right-justified. On the second line I need a report description centered with the name of the report right-justified. I couldn't get an example of the output to paste in correctly to this text field so hopefully this description will suffice, it seems pretty standard.

I retrieve the date, institute name, report description and report name from the database. So those fields are variable in size. I thought something like this would work but it does not right-justify or center correctly:

println String.format("%-${maxColumns}s %s %${maxColumns}s", dbDateTime.format('MMMMM d, yyyy'), institution, 'Page: 1')
println String.format("%-${maxColumns}s %s %${maxColumns}s", '', jobTitle, programName)

I set maxColumns to 80, the character limit. Any help is appreciated, I've searched high and low for this! Thanks!

Upvotes: 3

Views: 9533

Answers (1)

tim_yates
tim_yates

Reputation: 171154

A quick and dirty solution might be to do something like this:

def header( int maxWidth=80, ...text ) {
    def cols = maxWidth / text.size()
    def idx = 0
    text.inject( '' ) { s, t ->
        idx++
        if( t instanceof String ) {
            s += t.center( (int)cols )
        }
        else {
            switch( t.align ) {
                case 'left'  : s += t.text.padRight( cols, t.pad ?: ' ' ) ; break
                case 'right' : s += t.text.padLeft(  cols, t.pad ?: ' ' ) ; break
                default      : s += t.text.center(   cols, t.pad ?: ' ' )
            }
        }
        if( s.length() < Math.ceil( cols * idx ) && s.length() < maxWidth ) s += ' '
        s
    }
}

You can then pass it a list of Maps like:

def text = header( [ text:dbDateTime.format( 'MMMMM d, yyyy' ), align:'left' ],
                   [ text:'woo', pad:'-' ],
                   [ text:'Page 1', align:'right' ] )

And printing this will give you:

August 12, 2013            -----------woo------------                     Page 1

Obviously this doesn't handle situations where maxWidth isn't big enough to hold all fields, and probably a few other cases, but it might be a good start?

Upvotes: 3

Related Questions