triming blank spaces


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



Copy this code and paste it in your HTML
  1. public static String deleteBlanks(String s) {
  2. String result = "";
  3. for (int i=0; i<s.length(); i++) {
  4. if (!s.substring(i, i+1).equals(" ")) {
  5. result = result + s.substring(i, i+1);
  6. }
  7. }
  8. return result;
  9. }
  10.  
  11.  
  12. --------------------------------------------------------------
  13.  
  14. Use regular expressions to replace sequences of one or more spaces with nothing:
  15.  
  16. # let remove_blanks = Str.global_replace (Str.regexp "[ ]+") "";;
  17. val remove_blanks : string -> string = <fun>
  18.  
  19. For example:
  20.  
  21. # remove_blanks "He llo w orl d!";;
  22. - : string = "Helloworld!"
  23.  
  24. Another solution, using the Micmatch library and the POSIX definition of a blank, i.e. space or tab:
  25.  
  26. # let remove_blanks = REPLACE blank -> "";;
  27. val remove_blanks : ?pos:int -> string -> string = <fun>
  28. # remove_blanks "He llo w orl d!";;
  29. - : string = "Helloworld!"
  30.  
  31. Or directly:
  32.  
  33. # (REPLACE blank+ -> "") "He llo w orl d!";;
  34. - : string = "Helloworld!"
  35.  
  36. For replacing spaces only, use the following variant:
  37.  
  38. # (REPLACE " "+ -> "") "He llo w orl d!";;
  39. - : string = "Helloworld!"

URL: http://www.codecodex.com/wiki/index.php?title=Remove_blanks_from_a_string

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.