How to format a string with spaces based on a specified length?

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...

, - .

, , .

+4
2

@Test
public void isCorrectLength() {
    String value = StringUtils.format("Went to the slope and snowboarded for hours., 103);
    assert(value.length() == 103);
}

, :

int spaces = emptyCharacters / words.length - 1;

(66/8) - 1) = 7,25, for, .25 , .

, int, 0.25, double .

, 0,25 1, reset .

    double spaces = (double)emptyCharacters / (double)words.length - 1.0;

    double extraSpace = spaces % 1;
    double counter = 0;
    for (String word : words) {
        counter++;

        sb.append(word);
        for (int i = 0; i <= spaces; i++) {
            sb.append(" ");
        }

        if ((counter * extraSpace) >= 1) {
             sb.append(" "); // This is the extra space.
             counter = 0;
        }
    }

- . , . , , . , 0,25 2 . . ( 1, .)

.

    double spaces = (double)emptyCharacters / (double)words.length - 1.0;

    double extraSpace = spaces % 1;
    double counter = 0;
    int wordIndex = 0;
    for (String word : words) {
        counter++;
        wordIndex++;

        sb.append(word);
        for (int i = 0; i <= spaces; i++) {
            sb.append(" ");
        }

        if ((counter * extraSpace) >= 1) {
             sb.append(" "); // This is the extra space.
             counter = 0;
        }

        if ((wordIndex == words.length - 1) && (counter * extraSpace) > 0) {
            sb.append(" "); // This accounts for remainder.
        }
    }

, , , :

@Test
public void isCorrectLength() {
    String value = StringUtils.format("We went to the giant slope and snowboarded for hours., 103);
    assert(value.length() == 103);
}
+2
  • , .
  • , ( - ).
  • " ", ( - 1).
  • " ", , (. 2).
  • , , , ..

    private static String formatString (String , int length) {   //   String [] words = sentence.split( "\ s +" );

    // calc the char length of all words
    int wordsLength = 0;
    for (String w: words) {
        wordsLength += w.length();
    }
    
    // find the number of space blocks and initialize them
    int spacesLength = length - wordsLength;
    String[] spaceBlocks = new String[words.length - 1];
    Arrays.fill(spaceBlocks, "");
    
    // distribute spaces as evenly as possible between space blocks
    int spacesLeft = spacesLength;
    int k = 0;
    while (spacesLeft > 0) {
        spaceBlocks[k++] += " ";
        if (k == spaceBlocks.length) {
            k = 0;
        }
        spacesLeft--;
    }
    
    // assemble the buffer: for each word, print the word, then a spaces block, and so on
    StringBuilder b = new StringBuilder();
    for (int i = 0; i < words.length; i++) {
        b.append(words[i]);
        if (i < spaceBlocks.length) {
            b.append(spaceBlocks[i]);
        }
    }
    return b.toString();
    

    }

    public static void main (String [] args) {   String s;    t;

    s = "Hello, spaces.";
    t = formatString(s, 50);
    System.out.println(String.format("\"%s\" (length=%d)", t, t.length()));
    
    s = "Hello, spaces.";
    t = formatString(s, 51);
    System.out.println(String.format("\"%s\" (length=%d)", t, t.length()));
    
    s = "Good day, spaces.";
    t = formatString(s, 52);
    System.out.println(String.format("\"%s\" (length=%d)", t, t.length()));
    
    s = "The quick brown fox.";
    t = formatString(s, 53);
    System.out.println(String.format("\"%s\" (length=%d)", t, t.length()));
    
    s = "Ask not what your country can do for you.";
    t = formatString(s, 54);
    System.out.println(String.format("\"%s\" (length=%d)", t, t.length()));
    
    s = "Ask not what your country can do for you, Bob.";
    t = formatString(s, 55);
    System.out.println(String.format("\"%s\" (length=%d)", t, t.length()));
    

    }

"Hello,                                     spaces." (length=50)
"Hello,                                      spaces." (length=51)
"Good                   day,                  spaces." (length=52)
"The            quick            brown            fox." (length=53)
"Ask   not   what   your   country   can  do  for  you." (length=54)
"Ask  not  what  your  country  can  do  for  you,  Bob." (length=55)

, , .

( , , , ..). .

+1

Source: https://habr.com/ru/post/1655260/


All Articles