String. Trim () reveal the truth

Source: Internet
Author: User

At the last codereview meeting of the department, I left a homework question. What did the string. Trim () method do for us? Is it just to remove spaces at both ends of the string?

A long time ago, just a few hours ago, I thought that the trim () method was to delete the space characters at both ends of the string. In fact, I was wrong and the error was too outrageous.

First, we use relector to decompile the string class and find the trim () method:

 
Public StringTrim (){Return This. Trimhelper (whitespacechars, 2 );}

 

(Narrator: THE relector tool is really easy to use, haha)

It may be strange to see it here (I am also). Isn't the trim () method just remove the spaces at both ends? Why is there a trimhelper method?

The trimhelper method has two parameters. The first parameter is whitespacechars, and the first is uppercase.ArticleAs expected:

 
Internal Static Readonly Char[] Whitespacechars;

 

Here we just define it, there is no value assignment, and it is static. Let's look at the constructor and find it:

 
Constructor of the string classStaticString () {empty =" "; Whitespacechars =New Char[] {'\ T',' \ n', '\ V',' \ F', '\ R',', '\ x0085 ', '\ x00a0', 'taobao ','','','','','','','','', 'hangzhou', '\ u2028', '\ u2029 ','',''};}

 

Whitespacechars is assigned a value in the string's static constructor.
This article is written in Notepad (the speed at which word 07 is opened is not flattering ).CodeA change occurred when copying from reflector to notepad (SEE ):

The TRIM method deletes the characters at both ends of the string? I firmly guess.

Continue our exploration and decompile trimhelper directly. Wow, maybe this is what I want. The private trimhelper method:

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] = 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 precise analysis and operation of the CPU of my brain, I basically know what this method is.

The trimhelper method has two parameters:

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

The second parameter, trimtype, is the type that identifies trim. Currently, three trimtype values are available.When0Removes the white space characters in the string header.1Remove the white space at the end of the string and input other values (such2) Removes spaces at both ends of the string.

Finally, let's take a look at the method for truly executing string truncation:

 Internalsubstring  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 ;}

 

Why does Microsoft use pointers? For the first time, the efficiency should be relatively high.
Summary:
The string. Trim () method removes both ends of the string, not just space characters. It can remove a total of 25 characters:
('\ T',' \ n', '\ V',' \ F', '\ R',', '\ x0085', '\ x00a0 ', 'taobao ','', 'hangzhou', 'hangzhou', '', '\ u2028', '\ u2029 ','','')
If you want to retain one or more of them (for example, \ t tab, \ n line feed), use TRIM with caution.

Please note that,The deletion process of trim is from the outside to the inside until a non-blank character is encountered. Therefore, no matter how many consecutive blank characters before and after the trim is deleted.

 

At last, we attached two related methods (also provided directly by the string class) to remove the trimstart Method for white spaces in the string header and the trimend Method for white spaces at the end of the string:

 Trimstart and trimend Methods  Public   String Trimstart ( Params   Char [] Trimchars ){ If (Trimchars = Null ) | (Trimchars. Length = 0) {trimchars = whitespacechars ;} Return   This . Trimhelper (trimchars, 0 );} Public   String Trimend ( Params   Char [] Trimchars ){ If (Trimchars = Null ) | (Trimchars. Length = 0) {trimchars = whitespacechars ;} Return  This . Trimhelper (trimchars, 1 );}

 

I did verify the above CPU analysis results.

If you want to remove any other characters at both ends of the string, you can consider trim's heavy load brother: String. Trim (char []) to input an array of the characters you want to remove.

Source code:

 
Public StringTrim (Params Char[] Trimchars ){If(Trimchars =Null) | (Trimchars. Length = 0) {trimchars = whitespacechars ;}Return This. Trimhelper (trimchars, 2 );}

Space! = Blank characters. use TRIM ('') to delete spaces ('');

 

Finally, I would like to give you a question:

String S = "from dual Union all ";
S = S. Trim (). trimend ("Union all". tochararray ());

What is the final value of S? Haha (I just saw this question on another big blog)

The blog garden has many cool people.

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.