Java.lang.String Trim () method detailed

Source: Internet
Author: User

What exactly does the String.Trim () method do for us, just to remove the spaces at both ends of the string?

Always thought that the trim () method is to delete the whitespace characters at both ends of the string, in fact I was wrong, and the wrong is more outrageous.

First I directly decompile the string class and find the Trim () method:

public string Trim () {return this. Trimhelper (Whitespacechars, 2);}

Trimhelper method has two parameters, the first parameter name Whitespacechars, the first letter altogether is uppercase, there must be articles, really do not I expected:

Internal static readonly char[] Whitespacechars;

Here just define it, no assignment, and it's static, let's look at the constructor to go, sure enough to find:

Static String ()

{Empty = " "; Whitespacechars = new char[] {'/t ', '/n ', '/V ', '/f ', '/R ', ' ', '/x0085 ', '/x00a0 ', '? ', '? ', '? ', '? ' , '? ', '? ', '? ', '? ', '? ', '? ', '? ', '? ', '? ', '/u2028 ', '/u2029 ', ', '? '}; }

The Trim method is to delete the characters at both ends of the string. I'm very determined to guess.

Continue our exploration, direct anti-compilation trimhelper, Wow, maybe this is what I want, private Trimhelper method:

Private string trimhelper (char[] trimchars, int trimtype) {    int  num = this. Length - 1;    int startindex = 0;    if   (trimtype != 1)     {         startindex = 0;        while  (startIndex <  this. Length)         {             int index = 0;             char ch = this[startIndex];             index = 0;             while  (index < trimchars.length)             {                 if  (trimchars[index] == ch)                  {                     break;                 }                 index++;             }            if  (index ==  Trimchars.length)             {                 break;             }            startindex++;         }    }    if  ( trimtype != 0)     {        num =  this. length - 1;        while  (num >=  StartIndex)         {             int num4 = 0;             char ch2 = this[num];             num4 = 0;             while  (num4 < trimchars.length)              {                if  (trimChars[num4]  ==&NBSP;CH2)                 {                      break;                 }                num4++;             }             if  (num4 == trimchars.length)              {                 break;            }             num--;        }     }    int length =  (Num - startindex)  + 1;    if  (length == this. Length)     {        return this;     }    if  (length == 0)     {         return empty;    }    return  this. Internalsubstring (Startindex, length, false);}

After analysis and operation, basically know what this method is.

The Trimhelper method has two parameters:

The first parameter, trimchars, is an array of characters to remove from both ends of the string;

The second parameter, Trimtype, is the type that identifies trim. It is now found that the value of Trimtype is 3. When 0 is passed in, the whitespace character at the head of the string is stripped , the white space character at the end of the string is passed in 1 , and other values (such as 2) are removed to remove whitespace characters at the ends of the string.

Finally, take a look at the actual method of string interception:

Private unsafe string internalsubstring (Int startindex, int length, bool  falwayscopy) {    if  ((startindex == 0)  &&  (length  == this. Length))  && !falwayscopy)     {         return this;    }    string str =  Fastallocatestring (length);    fixed  (char* chref = &str.m_ Firstchar)     {        fixed  (char*  Chref2 = &this.m_firstchar)         {             wstrcpy (chref, chref2 + startindex,  Length);        }    }     Return str;}

You used a pointer? First see, efficiency should be relatively high bar.
Finally, summarize:
The String.Trim () method removes both ends of the string, not just the space character , which altogether can remove 25 characters:
('/t ', '/n ', '/V ', '/f ', '/R ', ' ', '/x0085 ', '/x00a0 ', ' ', ' ', ' ', ' ', ' ', ', ', ', ', ', ', ', '? ', ' /u2028 ', '/u2029 ', ', '? ')


If you want to keep one or more of these (for example,/t tabs,/n newline characters,/R return characters, etc.), use the Trim method with caution.

Note that the trim removal process is out-of-the-way until a non-whitespace character is encountered, so that no matter how many consecutive whitespace characters are removed, it will be deleted.

Finally, we enclose two related methods (also directly provided by the string class) to remove the TrimStart method of the white-space character of the string and the TrimEnd method to remove the trailing whitespace character of the string:

TrimStart and TrimEnd methods

If you want to remove any other characters at both ends of the string, consider trimming his overloaded brother: String.Trim (char[]), passing in an array of which characters you want to remove.

The Source:

public string Trim (params char[] trimChars) {if (TrimChars = = null) | |    (Trimchars.length = = 0))    {trimChars = Whitespacechars; } return this. Trimhelper (TrimChars, 2);}

Space! = whitespace character, remove space use: Trim (');


Java.lang.String Trim () method detailed

Related Article

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.