Search code examples
substringnim-lang

substring in string in nim (in operator)


I wanted to verify substring existence in a string and came up with:
if "haystack".find("needle") != -1:

But I would have prefered: if "needle" in "haystack": as in python.
Though we get:

Error: type mismatch: got (string, string) but expected one of: proc contains[T](s: Slice[T]; value: T): bool proc contains[T](x: set[T]; y: T): bool proc contains[T](a: openArray[T]; item: T): bool

note that if you import strutils it starts to work.


Solution

  • You already gave the answer yourself, import strutils to get the contains proc for strings. Nim automatically used the contains proc for the in operator.