Check if a greeting string contains the word 'world'.

← Operators and Expressions · Ref: Q1099

Substring check:

  hasWorld <- greeting contains "world"
  noXyz <- greeting not contains "xyz"

Keyword operator, not a method call. Returns Boolean. See Q1101 for 'is in' collection membership.

Example

defines module qa.operators.containsnotcontains

  defines program

    ContainsNotContainsDemo()
      stdout <- Stdout()

      greeting <- "hello world"

      //Check substring is present
      hasWorld <- greeting contains "world"
      stdout.println(`Contains 'world': ${hasWorld}`)

      //Check substring is absent
      noXyz <- greeting not contains "xyz"
      stdout.println(`Not contains 'xyz': ${noXyz}`)
Other ways to ask this
  • I need to test whether a string includes a specific substring
  • In Java I'd use str.contains(). Write the EK9 substring check
  • Given a message string, verify it contains a keyword and also check for absence
  • Search for a substring inside a string using the contains operator

Coming from another language?

Java: str.contains(sub). Python: sub in str. Rust: str.contains(sub). Go: strings.Contains(). EK9: str contains sub — keyword, not method.

Keywords: string, check, substring, not contains, search, contains