94

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
John Doe
  • 1,250
  • 2
  • 9
  • 14

1 Answers1

147

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

if a.contains("bc") {
    do_something();
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Kevin Hoerr
  • 2,319
  • 1
  • 10
  • 21
  • What if I want to see if a string contains, say, one more more capital letters? – g.delgado Aug 25 '18 at 20:00
  • 12
    You should probably post that as a separate question. Personally, I'd try to use regex for that. – Kevin Hoerr Aug 26 '18 at 04:36
  • 5
    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. – David Jul 16 '22 at 01:52
  • how do i also get the index? – ihsan Jun 06 '23 at 17:10
  • If you check the docs, there is a [`String::find` method](https://doc.rust-lang.org/std/string/struct.String.html#method.find) that returns the index for characters or fuller string patterns – Kevin Hoerr Jul 11 '23 at 15:43