Java RegEx to replace 2 spaces with 1

This Comment will be submitted for moderation and will not be accessible to other users until it has been approved.


16 points

Hi,

I am looking for a quick way in Java to change the string:

" this is it "

to
"this is it"

I want to replace all multiple spaces with a single space. I also want all the spaces at the end and begining of the string to go away as well.



6 points

Use String trim() method to trim spaces at the begining and end of the string. For other spaces within words use:

mytext  = mytext.trim()
mytext = mytext.replaceAll("( )+", " ")

Anonymous's picture
Created by Anonymous

Post Comment

  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.