Trim, TrimStart, and TrimEnd

The Trim method, by default, removes all white space (spaces, tabs, and line breaks) from the beginning and end of a string. Consider the following example:

$string = " 
    This string has leading and trailing white space      " 
$string.Trim() 

The TrimStart and TrimEnd methods limit their operation to either the start or end of the string.

Each of the methods accepts a list of characters to trim. Consider the following example:

$string = '*__This string is surrounded by clutter.--#' 
$string.Trim('*_-#') 

The Trim method does not remove a string from the end of another. The string supplied in the previous example ('*_-#') is treated as an array. This can be seen in the definition of the method:

PS> 'string'.Trim

OverloadDefinitions
-------------------
string Trim(Params char[] trimChars)
string Trim()

A failure to appreciate this can lead to unexpected behavior. The domain name in the following example ends with the suffix, '.uk.net'. The goal is to trim the suffix from the end of the string. However, the method goes too far here, taking away part of the name:

PS> $string = 'magnet.uk.net' 
PS> $string.TrimEnd('.uk.net')

mag
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.107.253