tags:

views:

48

answers:

2

there's a text file

first second third
1 2 3
yes no ok
hmmmmmmm yep_a_long_word_it_is ahahahahahahha

what java functions /libs to use to align words so that they are looked like this (fixed width based on the longest column's length), let's say center align:

  first          second            third
    1              2                 3
    yes            no                ok
hmmmmmmm yep_a_long_word_it_is ahahahahahahha

You know, I need "JUSTIFY-FULL" functionality of Microsoft Word (Ctrl + J).

+2  A: 

See center(String, int) method of org.apache.commons.lang.StringUtils in Apache Commons Lang.

Link: http://commons.apache.org/lang/

Bolo
I knew Apache StringUtils had something ;)
EugeneP
Yep, it seems that They do not have a function I need :( This just centers the text, it'll add paddings to left and right. What I need is to create a long string and justify spaces equally between every word.
EugeneP
+1  A: 

I don't know of any libraries that will do this for you, but it is a pretty trivial programming task...

Make one pass through the data and measure the maximum length of a string in each column

Make a second pass through writing the data out with padding on either side of each datum to make the width the same as the maximum.

Write yourself a function that pads a String on either end to a fixed length.

EDIT: just seen the other answer about the Apache commons string centering utility - that'll save you having to write one, so long as you don't mind adding that dependency to you rproject.

Simon
@Simon Not sure that is what I'm looking for. I need justify-full, ctrl+j in Word. This function seem to work like justify-center. Maybe they have another function in StringUtils?
EugeneP
in that case there's a good argument to write one yourself. This really isn't that hard a problem, have a crack at it.
Simon
just a sec... full justify is a paragraph formatting activity and requires hyphenation. I thought that your file had a line end between third and 1, 3 and yes and ok and hmmmmm. Are you saying that these need to form a contiguous paragraph given a line width? That's what I think full-justify implies.
Simon
@Simon No, it does not really require hyphenation in my case. I was not exact maybe. But you got already the idea. We need to find the longest (in chars) line. That'll be the lineMaxLength. Then, every shorter length of the file should be padded, but EQUALLY.
EugeneP
4 words, means at most 5 space paddings. leftmost and rightmost paddings of the longest string will be of 0 length. In shorter strings all 5 paddings (differences in spaces between adjacent words) will be non-empty.
EugeneP
so, you are stretching every row in the file so its length is the same as the longest length of any row and spreading any necessary padding equally between the words, right?
Simon