Firstly I'll just state that this is a question from my uni course, as such I would really appreciate an explanation of any code used.
Essentially I need to take a string in the form of a sentence (for instance):
*** the character > represents a space ***
This>is>a>test>string.
And then give the ability to justify the words so that a given number of spaces pad the string out (for instance):
Number of characters long the string is to be: 36
This>>>>>is>>>>>a>>>>test>>>>string.
Like in the example above, if it is not possible for the number of spaces between the words to be equal, then the "extra space" needs to be added on the left.
To clarify what I mean:
Original string length: 22 Characters
"Justified" string length: 36 Characters
Number of spaces that need to be added: 14
Number of words (or tokens): 5
Number of gaps between words to put spaces in: 4
So 14 extra spaces divided by 4 gaps means 3.5 spaces added to each gap, so two gaps must have 4 spaces added to them, and two gaps must have 3 spaces added to them. The spaces need to be added in order from left to right.
Having looked through the API it seems String.split is recommended over String Tokenizer now (I've used String Tokenizer before, although not for anything remotely complicated, but not String Split). Here's as far as I've got before becoming stuck (a bit of the code is partly poached from another thread on these forums):
.
.
.
justifiedStringLength is a variable for the method
String[] result = "This is a test string".split("\\s");
((justifiedStringLength - String.length) / (result.length - 1) = spacesToBeAddedToEachGap)
for (int x=0; x<result.length; x++)
System.out.print(result[x]);
I figure that I need to somehow work out how to:
Turn spacesToBeAddedToEachGap into a set (perhaps an array?) of whole numbers.
And then work out how to concatenate that new string into the final string....
I'm lost and confused... Am I making this far more complicated than it needs to be?
Any help would be very much appreciated.