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

StringRust

String Problem Overview


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.

String Solutions


Solution 1 - String

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohn DoeView Question on Stackoverflow
Solution 1 - StringKevin HoerrView Answer on Stackoverflow