An attempt to create a method in Java formats a string by stretching the contents (by placing the appropriate number of spaces) of the buffer depending on the length. Thus, based on a certain length, the first character of the string is in the first index, and the last character is in the most recent index.
public static String format(String sentence, int length) {
if (sentence.length() >= length) {
return sentence;
}
StringBuilder sb = new StringBuilder();
String[] words = sentence.split("\\s+");
int usedCharacters = 0;
for (String word : words) {
usedCharacters += word.length();
}
int emptyCharacters = length - usedCharacters;
int spaces = emptyCharacters / words.length - 1;
for (String word : words) {
sb.append(word);
for (int i = 0; i <= spaces; i++) {
sb.append(" ");
}
}
return sb.toString();
}
For this unit test, this works:
@Test
public void isCorrectLength() {
String value = StringUtils.format("brown clown", 20);
assert(value.length() == 20);
}
So here is the maximum buffer size: 20
Total number of characters used: 10
Total number of unused characters: 10
The end result (if you print the line):
brown clown
"n" in the clown has an index of 20 ...
However, there is a marginal case with the following test (which causes it to break):
@Test
public void isCorrectLengthWithLongerSentence() {
String value = StringUtils.format("Love programming Java using Eclipse!", 50);
assert(value.length() == 50);
}
Buffer size: 50
Total Characters Used: 25 Total Unused Characters: 25
Spaces: 3
: 48
( ):
Love programming Java using Eclipse!
48 50?
"!" "Eclipse", 50 48...
, - .
, , .