"Java" About removing spaces

Source: Internet
Author: User

The first thing to declare is that the trim () method, although everyone knows, but this thing is caught in the error of removing all the blanks, trim () can only remove the characters before and after the string, for the middle character cannot be processed.

If you want to remove all spaces, still use the ReplaceAll method, such as the following statement:

Space.replaceall ("\\s", "" ");
Using regular expressions, \\s first Find all the blanks, and then replace them directly,

It is also possible to write directly as follows, but it seems that in some places there is a very magical situation where there is no power:

Space.replaceall ("," "");
If you want to clear the extra space into a space, use the following method:

Space.replaceall ("\\s+", "" ");
The following + indicates that if a space is encountered, then everything after the match, that is, matches 1~x spaces,

Of course:

Space.replaceall ("+", "");
However, some cases still do not give force, in the regular expression of writing spaces, or written \\s, Standard point good.

At the same time note if Java EE programming, pay attention to pass over is not & nbsp;

In summary, such as the following procedures:

public class Clearspace {public static void main (string[] args) {String space= "s   SS S"; System.out.println (Space.trim ()); System.out.println (Space.replaceall ("+", "")); System.out.println (Space.replaceall ("\\s+", "")); System.out.println (Space.replaceall ("\\s", ""));}}

The operating result is:


Pay attention to the string after processing, re-assigned to the original string Oh!

"Java" About removing spaces

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.