Joshua
Joshua

Reputation: 2109

F# case insensitive string compare

Is there a syntactically cleaner way to preform a case insensitive string comparison in F# than the following

System.String.Equals("test", "TeSt", System.StringComparison.CurrentCultureIgnoreCase)

Upvotes: 7

Views: 9264

Answers (4)

mud dog
mud dog

Reputation: 1

// Contains substring
(str1.ToUpper()).Contains (str2.ToUpper())
// Equality
(str1.ToUpper()).Contains (str2.ToUpper())

Upvotes: -1

Maslow
Maslow

Reputation: 18746

For any interested, a partial active pattern for this:

let (|InvariantEqualI|_|) (str:string) arg = 
  if String.Compare(str, arg, StringComparison.InvariantCultureIgnoreCase) = 0
  then Some() else None
let (|OrdinalEqualI|_|) (str:string) arg = 
  if String.Compare(str, arg, StringComparison.OrdinalIgnoreCase) = 0
  then Some() else None

Upvotes: 0

ssp
ssp

Reputation: 1722

Also, you can use F# type extensions mechanics:

> type System.String with
-   member s1.icompare(s2: string) =
-     System.String.Equals(s1, s2, System.StringComparison.CurrentCultureIgnoreCase);;
> "test".icompare "tEst";;
val it : bool = true

Upvotes: 11

Darin Dimitrov
Darin Dimitrov

Reputation: 1039220

How about writing an extension method to make this shorter.

Upvotes: 4

Related Questions