fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.util.regex.*;
  5. import java.lang.*;
  6. import java.io.*;
  7.  
  8. /* Name of the class has to be "Main" only if the class is public. */
  9. class Ideone
  10. {
  11.  
  12. public static String limiter(String str, int lim) {
  13. str = str.trim().replaceAll(" +", " ");
  14. str = str.replaceAll("\n +", "\n");
  15. Matcher mtr = Pattern.compile("(?U)(.{1," + lim + "}\\b\\s*)|(.{0," + lim + "})").matcher(str);
  16. String newStr = "";
  17. int ctr = 0;
  18. while (mtr.find()) {
  19. if (ctr == 0) {
  20. newStr += mtr.group();
  21. ctr++;
  22. } else {
  23. newStr += "\n" + mtr.group();
  24. }
  25. }
  26. return newStr;
  27. }
  28.  
  29. public static void main (String[] args) throws java.lang.Exception
  30. {
  31. // your code goes here
  32. int limit = 7;
  33. String str = " The 123456789 456789 +-.,!@#$%^&*();\\/|<>\"\' fox jumpeded over the uf\n 2 3456 green fence ";
  34. String result = limiter(str, limit);
  35. System.out.print(result);
  36. }
  37. }
Success #stdin #stdout 0.11s 321600KB
stdin
Standard input is empty
stdout
The 
1234567
89 
456789 
+-.,!@#
$%^&*()
;\/|<>"
' fox 
jumpede
d over 
the uf

2 3456 
green 
fence