简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM