Trim trailing whitespace


/ Published in: Java
Save to your folder(s)

Works almost 9x faster than a regex pattern, and memory usage is better (because Matcher objects aren't created).


Copy this code and paste it in your HTML
  1. /* instead of
  2. Pattern p = Pattern.compile("[\\s]+$");
  3. // start timing
  4. p.matcher(str).replaceAll("");
  5.  
  6. The alternative method below averages 400ns, compared to 3500ns of the regex above */
  7.  
  8. public static String trimEnd(String str) {
  9. int len = str.length();
  10. char[] val = str.toCharArray();
  11.  
  12. while ((0 < len) && (val[len - 1] <= ' ')) {
  13. len--;
  14. }
  15.  
  16. return (len < str.length()) ? str.substring(0, len) : str;
  17. }
  18.  
  19.  
  20. /* Similarly, using a StringCharacterIterator is also faster (although memory usage is worse) - averages 500ns */
  21.  
  22. public static String trimEnd(String str) {
  23.  
  24. int len = str.length();
  25. for (char c = iter.last(); c != CharacterIterator.DONE && c <= ' '; c = iter
  26. .previous()) {
  27. len --;
  28. }
  29.  
  30. return ((len < str.length())) ? str.substring(0, len)
  31. : str;
  32. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.