public static String stringAligning(String stringToAlign, int lengthAlignment) { String fs = "%"+lengthAlignment+"s"; return String.format(fs,stringToAlign); }
If it is longer, it cuts, if it is shorter it adds.
The example adds leading spaces. To add spaces to the end of the line use "%-"+lengthAlignment+"s" .
Read about formatting strings .
Although it is not correct, but here is the complete solution of the problem step by step.
//Вводные данные String demo = "Пам парам пам пам пурум"; //строка int strSize = 60; //длинна, на которую ее надо натянуть нормализовав пробелы //Разбиваем строку на массив слов. String[] norma = demo.split("\\s+"); System.out.println(Arrays.toString(norma)); //[Пам, парам, пам, пам, пурум] //Вычисляем сумму символов всех слов int chCount = 0; for (int i = 0; i < norma.length; i++) { chCount += norma[i].length(); } System.out.println("chCount=" + chCount); //chCount=19 // Между N словами помещается N-1 пробел. Вычислим длинну "целого" пробела int padSize = (strSize - chCount)/(norma.length-1); System.out.println("padSize=" + padSize); //padSize=10 //Кроме "целых" пробелов у нас останется запас. int spaces = (strSize - chCount)%(norma.length-1); System.out.println("spaces=" + spaces); //spaces=1 //Формируем строку String result = norma[0]; for (int i = 1; i < norma.length; i++) { //Слово + пробелы перед ним. Так как будем испльзовать String.format int pad = padSize+norma[i].length(); //Если есть пробелы в запасе +1 if (spaces>0) { pad = pad+1; spaces--; } String sf = "%" + pad + "s"; result += String.format(sf,norma[i]); } //Итого System.out.println("123456789+123456789+123456789+123456789+123456789+123456789+"); System.out.println(result); //123456789+123456789+123456789+123456789+123456789+123456789+ //Пам парам пам пам пурум
pad. There are several methods . - enzo