Answer the question
In order to leave comments, you need to log in
Java. How to evenly distribute spaces so that the string becomes a given length?
How to evenly distribute spaces so that the string becomes the desired length? Spaces should not be added to the end of the line, but placed between words.
Answer the question
In order to leave comments, you need to log in
Good day to all!
Liked the problem, wrote:
package ru.bedward70.toster.q440809;
public class App {
public static void main(String[] args) {
final String origin = "Мама мыла раму!";
final String result = addSpaces(origin, 20);
System.out.println(" 12345678901234567890123456789012345678901234567890");
System.out.println("Origin: " + origin);
System.out.println("Result: " + result);
}
private static final String DELIMITER = " ";
private static String addSpaces(String origin, int count) {
// Validation | проверка от зацикливания
if (origin.indexOf(DELIMITER) == -1) {
throw new RuntimeException("No \"" + DELIMITER + "\" in \"" + origin + "\" string");
}
// work Buffer | Рабочий буфер
final StringBuilder sb = new StringBuilder(origin);
// Delimiter Point | Указатель, где происходит поиск делимитера
int point = 0;
// Cycle | Пока не набьем нужную длину
while (sb.length() < count) {
int index = sb.indexOf(DELIMITER, point);
// end text | Если конец текста, то начинаем с начала
if (index == -1) {
point = 0;
continue;
}
// is next the delimiter? | Если не последний делимитер в последовательности делимитеров, то это не наш случай - пропускаем
point = index + DELIMITER.length();
if (point == sb.indexOf(DELIMITER, point)) {
continue;
}
// Add delimiter | Нашли последний делимитер в последовательности делимитеров, то добавляем
sb.replace(point, point, DELIMITER);
point += DELIMITER.length();
}
return sb.toString();
}
}
collect a collection of words, calculate the sum of the lengths of all words, calculate the missing length, divide the sum of all words - 1 by the missing length, take the integer part, add after each word from position 0 to N - 1 (integer part) spaces, multiply the remainder of the calculations by N - 1, then either randomly place the remaining spaces, or simply go from position 0 and place 1 space after the word, eventually collecting the string. more or less evenly.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question