IndexOf and LastIndexOf

IndexOf and LastIndexOf may be used to locate a character or string within a string. IndexOf finds the first occurrence of a string, and LastIndexOf finds the last occurrence of the string. In both cases, the zero-based index of the start of the string is returned. If the character, or string, isn't present, the two methods will return -1:

$string = 'abcdefedcba' 
$string.IndexOf('b')     # Returns 1 
$string.LastIndexOf('b') # Returns 9 
$string.IndexOf('ed')    # Returns 6 

As -1 is used to indicate that the value is absent, the method is not suitable for statements based on an implicit Boolean. The index 0, a valid position, is considered to be false. The following example correctly handles the return value from IndexOf in a conditional statement:

$string  = 'abcdef' 
if ($string.IndexOf('a') -gt -1) {
'The string contains an a' }

The scope of the IndexOf and LastIndexOf methods can be limited using the start index and count arguments.

Methods that are able to locate a position within a string are useful when combined with other string methods, as shown here:

PS> $string = 'First,Second,Third'
PS> $string.Substring(
>> $string.IndexOf(',') + 1, # startIndex (6)
>> $string.LastIndexOf(',') - $string.IndexOf(',') - 1 # length (6)
>> )

Second

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

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