February 2019
Intermediate to advanced
626 pages
15h 51m
English
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
Read now
Unlock full access