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
ingives a plain yes or no for a substring.startswithandendswithanchor the test to either end.findreturns the index, or-1when there is no match.
Keywords and builtins used here
Stringdefmainprintvar
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.
Step 4 of 5 in Strings, step 21 of 26 in Language basics.