In general, some kind of string with a set of characters / words is given, you need to stretch it, to a specified length. So far, all I could squeeze out of myself was this kind of coarse code.

public static String stringAligning(String stringToAlign, int lengthAlignment) { String resultString = stringToAlign; StringBuilder sb = new StringBuilder(resultString); int temp = 1; if (stringToAlign.length() < lengthAlignment) { while (sb.length() < lengthAlignment) { for (int i = 1; i < sb.length(); i += temp) { if (resultString.charAt(i) == ' ') { sb.insert(i, ' '); temp = 2; }else { temp = 1; } } } } else { System.out.println("lengthAlignment number is lower than line"); } resultString = sb.toString(); return resultString; } 
  • If I understand correctly, this is a procedure that is traditionally called a pad . There are several methods . - enzo
  • so there add spaces or characters after only 1 word ... but I basically need to put after the skin word on the space (cycle), if at the end after last. the word length is still less than a given number, the cycle is repeated until the condition is true - Oleksandr

1 answer 1

 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+ //Пам парам пам пам пурум 
  • String hexwad = "adwd dawdaw dawdaw fwafawfawfa"; String hexrework = Util.stringAligning2 (hexwad, 80); System.out.println (hexrework); output gave "% s" and all - Oleksandr
  • @ user213177 Fixed a bug. % before s is superfluous. - Sergey Mitrofanov
  • probably got you already, right?) you gave me an example about stretching a line, adding leading or trailing spaces. My task is to make something like this "adwd (5 spaces) dawdaw (5 spaces) dawdaw (5 spaces) fwafawfawfa (5 spaces)" With your example, I now had the idea to break the line into words , then with each hold this trick with the addition of spaces, and then fold it back into a line ... How can I implement it even xs, but maybe there is also a function like this, only 1-2 lines? Or did you actually give it to me, I'm just from the "stupid-stupid" tribe? - Oleksandr
  • @ user213177 see update. Try to break the task into small questions and find the answer to them. Good luck. - Sergey Mitrofanov