IndexOf
A string
is contained in another. A character may also be present. With IndexOf
, and its friends LastIndexOf
, IndexOfAny
and LastIndexOfAny
we search for chars and strings.
For the most part, F# string
methods are the same as C# ones. The calling syntax is different: there are no parentheses required, and the "let" keyword is used.
Here we use IndexOf
. We have a string
containing 3 words—fish, frog and dog. We use IndexOf
to search for "frog" and "bird." For "frog" we get the index 5.
IndexOf
method returns -1. This is a special value meaning "not found."let words = "fish frog dog" // Call IndexOf on a string. // ... The word "frog" exists but "bird" does not. let frogPosition = words.IndexOf("frog") let birdPosition = words.IndexOf("bird") // Print our results. printfn "%d" frogPosition printfn "%d" birdPosition5 -1
LastIndexOf
With this function we search from the right to the left (backwards in order). So LastIndexOf
returns the last position of the substring. This is the opposite of IndexOf
.
let codes = "abc def abc def" // Use IndexOf and LastIndexOf to search from the left and right. let firstAbc = codes.IndexOf "abc" let lastAbc = codes.LastIndexOf "abc" // The substring "abc" was located in different places. printfn "%d" firstAbc printfn "%d" lastAbc0 8
Contains
This is a simple method. It returns true if the substring is contained in the string, and false if not. It is a simplification of IndexOf
.
IndexOf
for the same functionality as Contains
.let title = "Areopagitica" // The string contains this substring. let test1 = title.Contains "ca" // But this substring is not found. let test2 = title.Contains "cat" // Print the results as booleans. printfn "%b" test1 printfn "%b" test2true false
IndexOfAny
This method (and its friend LastIndexOfAny
) receives a char
array argument. We use a special F# syntax with vertical bars to specify a char
array.
LastIndexOfAny
searches in reverse.let colors = "green orange red blue" // Find first index of any of the letters in the char array. let firstOfSet1 = colors.IndexOfAny [|'o'; 'b'|] printfn "First o or b: %d" firstOfSet1 printfn "%s" (colors.Substring firstOfSet1) // Use another char array. let firstOfSet2 = colors.IndexOfAny [|'b'; 'g'|] printfn "First b or g: %d" firstOfSet2 printfn "%s" (colors.Substring firstOfSet2) // Use LastIndexOfAny. let lastOfSet1 = colors.LastIndexOfAny [|'b'; 'l'; 'u'|] printfn "Last b or l or u: %d" lastOfSet1 printfn "%s" (colors.Substring lastOfSet1)First o or b: 6 orange red blue First b or g: 0 green orange red blue Last b or l or u: 19 ue
In F# we can use a for
-loop to search for substrings in a string
. But IndexOf
is simpler. With IndexOf
and its related methods, we must handle -1 when nothing is found.