115

I'm trying to find whether a substring is in a string. In Python, this involves the in operator, so I wrote this code:

let a = "abcd";
if "bc" in a {
    do_something();
}

I get a strange error message:

error: expected `{`, found `in`
 --> src/main.rs:3:13
  |
3 |       if "bc" in a {
  |  _____________-^
4 | |         do_something();
5 | |     }
  | |_____- help: try placing this code inside a block: `{ a <- { do_something(); }; }`

The message suggests that I put it in a block, but I have no idea how to do that.

1 Answer 1

178

Rust has no such operator. You can use the String::contains method instead:

if a.contains("bc") {
    do_something();
}
Sign up to request clarification or add additional context in comments.

5 Comments

What if I want to see if a string contains, say, one more more capital letters?
You should probably post that as a separate question. Personally, I'd try to use regex for that.
For anyone else who comes to this. you can do thing.contains(['A', 'B', 'C]) to check if thing has capitalized A, B, or C in it.
how do i also get the index?
If you check the docs, there is a String::find method that returns the index for characters or fuller string patterns

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.