Advertisement
Guest User

Untitled

a guest
Aug 30th, 2016
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. public class PlaceWords {
  2.  
  3. public void placeWords(String string, int maxLen) {
  4. String[] words = string.split(" ");
  5. //System.out.println("words length " + words.length);
  6. int i = 0;
  7. int j = i+1;
  8. while (i < words.length && j <= words.length) {
  9. int count = words[i].length();
  10. while (count < maxLen && j < words.length) {
  11. if (count + words[j].length() + 1 > maxLen) {
  12. break;
  13. }
  14.  
  15. count = count + 1 + words[j].length();
  16. j++;
  17. }
  18.  
  19. //System.out.println("I : " + i + " , j : " + j + " count : " + count);
  20. StringBuilder sb = new StringBuilder();
  21. int avgSpaces = (maxLen - count)/(j-i);
  22. int modSpaces = (maxLen - count)%(j-i);
  23. System.out.println("mod : " + modSpaces);
  24. for (int k = i; k < j; k++) {
  25. sb.append(words[k]);
  26. sb.append(" ");
  27. for (int l = 0; l < avgSpaces; l++) {
  28. sb.append(" ");
  29. }
  30. if (modSpaces > 0) {
  31. sb.append(" ");
  32. modSpaces--;
  33. }
  34. }
  35. //sb.setLength(sb.length() - 1);
  36. System.out.println(sb.toString());
  37. i = j;
  38. j++;
  39. }
  40. }
  41.  
  42. public static void main(String[] args) {
  43. PlaceWords placeWords = new PlaceWords();
  44. placeWords.placeWords("This is a sample test for this excercise", 14);
  45. }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement