Advertisement
Guest User

Untitled

a guest
Jul 20th, 2014
310
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1.  
  2. public static String wrap(final String str, int wrapLength,
  3. String newLineStr, final boolean wrapLongWords) {
  4. if (str == null) {
  5. return null;
  6. }
  7. if (newLineStr == null) {
  8. newLineStr = System.getProperty("line.separator");
  9. }
  10. if (wrapLength < 1) {
  11. wrapLength = 1;
  12. }
  13. final int inputLineLength = str.length();
  14. int offset = 0;
  15. final StringBuilder wrappedLine = new StringBuilder(
  16. inputLineLength + 32);
  17.  
  18. while (inputLineLength - offset > wrapLength) {
  19. if (str.charAt(offset) == ' ') {
  20. offset++;
  21. continue;
  22. }
  23. int spaceToWrapAt = str.lastIndexOf(' ', wrapLength + offset);
  24.  
  25. if (spaceToWrapAt >= offset) {
  26. // normal case
  27. wrappedLine.append(str.substring(offset, spaceToWrapAt));
  28. wrappedLine.append(newLineStr);
  29. offset = spaceToWrapAt + 1;
  30.  
  31. } else {
  32. // really long word or URL
  33. if (wrapLongWords) {
  34. // wrap really long word one line at a time
  35. wrappedLine.append(str.substring(offset, wrapLength
  36. + offset));
  37. wrappedLine.append(newLineStr);
  38. offset += wrapLength;
  39. } else {
  40. // do not wrap really long word, just extend beyond limit
  41. spaceToWrapAt = str.indexOf(' ', wrapLength + offset);
  42. if (spaceToWrapAt >= 0) {
  43. wrappedLine
  44. .append(str.substring(offset, spaceToWrapAt));
  45. wrappedLine.append(newLineStr);
  46. offset = spaceToWrapAt + 1;
  47. } else {
  48. wrappedLine.append(str.substring(offset));
  49. offset = inputLineLength;
  50. }
  51. }
  52. }
  53. }
  54.  
  55. // Whatever is left in line is short enough to just pass through
  56. wrappedLine.append(str.substring(offset));
  57.  
  58. return wrappedLine.toString();
  59. }
  60.  
  61. public static String wrap(final String str, final int wrapLength) {
  62. return wrap(str, wrapLength, null, false);
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement