Home
F#
Loop Over String Chars
This page was last reviewed on Dec 22, 2023.
Dot Net Perls
Loop, string chars. While F# programs can use many advanced features, often they need to perform simpler tasks like looping over a string. This can be done in many ways in F#.
for
Shows a string loop
For the least complex looping requirements, a for-in loop is best. But if we need the index of each character, a for-to loop is a better choice.
Example. For clarity, we use a string with the value "abc". Then we iterate over its characters, in forward and reverse order, in different ways.
Version 1 This is the easiest way to loop over the characters. But it does not give us the indexes of each char.
Version 2 With for-in, we can implement a reverse loop by passing the string to Seq.rev first.
Seq
Version 3 We can iterate over indexes, and then access each char by index, with a for-to loop.
Version 4 It is possible to access the characters from the string with the Chars accessor.
Version 5 For a reverse loop with indexes, we can use for downto—this is a decrementing index loop.
Shows a string loop
let value = "abc" // Version 1: use for-in. for c in value do printfn $"For-in: {c}" // Version 2: use for-in with Seq.rev for reverse loop. for c in Seq.rev value do printfn $"Seq.rev: {c}" // Version 3: use for-to loop. for i = 0 to value.Length - 1 do let c = value[i] printfn $"For-to []: {c}" // Version 4: Use for-to loop with Chars. for i = 0 to value.Length - 1 do let c = value.Chars(i) printfn $"For-to Chars: {c}" // Version 5: use for-downto loop for reverse loop. for i = value.Length - 1 downto 0 do let c = value[i] printfn $"For-downto: {c}"
For-in: a For-in: b For-in: c Seq.rev: c Seq.rev: b Seq.rev: a For-to []: a For-to []: b For-to []: c For-to Chars: a For-to Chars: b For-to Chars: c For-downto: c For-downto: b For-downto: a
Summary. Looping is often done in F#, and looping over strings is a common requirement as well. With for-in and for-to, we have a variety of powerful loops to choose from.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 22, 2023 (new).
Home
Changes
© 2007-2024 Sam Allen.