John Doe
John Doe

Reputation: 1490

How to check if a string contains a substring in Rust?

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.

Upvotes: 112

Views: 99450

Answers (1)

Kevin Hoerr
Kevin Hoerr

Reputation: 2609

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

if a.contains("bc") {
    do_something();
}

Upvotes: 174

Related Questions