typestar

Searching inside a string in Mojo

Four ways to ask whether, or where, some text appears.

def main():
    var line = String("mojo: python syntax, compiled speed")
    print("python" in line)
    print(line.startswith("mojo"))
    print(line.endswith("speed"))
    print(line.find("compiled"))
    print(line.find("rust"))

How it works

  1. in gives a plain yes or no for a substring.
  2. startswith and endswith anchor the test to either end.
  3. find returns the index, or -1 when there is no match.

Keywords and builtins used here

The run, in numbers

Lines
7
Characters to type
207
Tokens
60
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 42 seconds.

Type this snippet

Step 4 of 5 in Strings, step 21 of 26 in Language basics.

← Previous Next →