Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class PlaceWords {
- public void placeWords(String string, int maxLen) {
- String[] words = string.split(" ");
- //System.out.println("words length " + words.length);
- int i = 0;
- int j = i+1;
- while (i < words.length && j <= words.length) {
- int count = words[i].length();
- while (count < maxLen && j < words.length) {
- if (count + words[j].length() + 1 > maxLen) {
- break;
- }
- count = count + 1 + words[j].length();
- j++;
- }
- //System.out.println("I : " + i + " , j : " + j + " count : " + count);
- StringBuilder sb = new StringBuilder();
- int avgSpaces = (maxLen - count)/(j-i);
- int modSpaces = (maxLen - count)%(j-i);
- System.out.println("mod : " + modSpaces);
- for (int k = i; k < j; k++) {
- sb.append(words[k]);
- sb.append(" ");
- for (int l = 0; l < avgSpaces; l++) {
- sb.append(" ");
- }
- if (modSpaces > 0) {
- sb.append(" ");
- modSpaces--;
- }
- }
- //sb.setLength(sb.length() - 1);
- System.out.println(sb.toString());
- i = j;
- j++;
- }
- }
- public static void main(String[] args) {
- PlaceWords placeWords = new PlaceWords();
- placeWords.placeWords("This is a sample test for this excercise", 14);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement