How to check if a string contains only alphabets in F #
I have a string that should only contain alphabets. To check that I have written the following code
let isCorrectString(str:string) =
let isInRange x = (x > 64 && x < 91 ) || (x > 96 && x < 123) || x = 32
not (str.Any(fun ch -> not (isInRange (ch :?> int)) ))
I am obviously using LINQ's extension method `Any '. Is there a better way to write the above code?
+3
source to share
1 answer
If you just want to make sure this is correct, you can do:
let isCorrectString(str:string) =
let isInRange x = (x > 64 && x < 91 ) || (x > 96 && x < 123) || x = 32
let bad =
str
|> Seq.map (fun c -> isInRange(int c))
|> Seq.exists (fun b -> b = false)
not bad
Note that this might be a simpler alternative:
let isCorrectString(str:string) =
str
|> Seq.forall (fun c -> System.Char.IsLetter(c) || c = ' ')
Or, if you prefer:
let isCorrectString(str:string) =
str
|> Seq.tryFind (fun c -> not(System.Char.IsLetter(c) || c = ' '))
|> Option.isNone
+4
source to share