About the Java implementation of the extension of removing contiguous spaces

Source: Internet
Author: User

The first essay, the technical content is low, as a note to yourself record a study at this stage. (*^__^*) ...

The code for removing contiguous spaces in Java is simple:

 Public Static string formatString (String sourcestring) {        return sourcestring.replaceall ("+", "");    } 
View Code

For example, the input string "a B C D", the call function processing can output "ABCD." ReplaceAll ("+", "") is the removal of all contiguous spaces and can also be used replaceall ("\\s+", "") matches any of the whitespace characters, such as spaces, tabs, page breaks, and so on, removing any contiguous whitespace characters.

However, see the online Post said ReplaceAll method efficiency is low, so slowly studied, can be optimized for this code.

Static  Publicstring Spacecharacter (String sourcestring) {if(Sourcestring! =NULL) {            intLen =sourcestring.length (); if(Len > 0) {                Char[] Dest =New Char[Len]; intDestpos = 0;  for(inti = 0; i < Len; ++i) {Charc =Sourcestring.charat (i); if(!Character.iswhitespace (c)) {Dest[destpos++] =C; }                }                return NewString (dest, 0, Destpos); }        }        returnsourcestring; }
View Code

How does this code come out, you can look at this blog: http://www.2cto.com/kf/201406/309388.html

Optimized code execution is really more efficient than direct replaceall.

(PS: There is a small thing about the i++ and ++i of the For loop, there is a for loop in the efficiency of i++ and ++i, but the author does not let the reprint is not posted here ~ only their own search)

About the Java implementation of the extension of removing contiguous 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.