Right trim in Java


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

I made this because org.apache.commons.lang.StringUtils does not have this method. I used this because i was dealing with a legacy db where all fields were char. trailing spaces were a pita.


Copy this code and paste it in your HTML
  1. public static String rightTrim(String data)
  2. {
  3. if(data==null)
  4. return null;
  5.  
  6. char[]arr=data.toCharArray();
  7. char[] newArr=new char[1];
  8. int pos=0;
  9. //worst algorithm ever. but works!
  10. for (int i = 0; i < arr.length; i++)
  11. {
  12. pos=(arr.length-1)-i;
  13. // System.out.println("pos["+pos+"] i["+i+"] ["+arr[pos]+"]");
  14. if(arr[pos]!=' ')
  15. {
  16. newArr= new char[pos+1];
  17. System.arraycopy(arr, 0, newArr, 0, pos+1);
  18. break;
  19. }
  20.  
  21. }
  22.  
  23. return new String(newArr);
  24. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.