HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howchecksubstringruststringcontains

Problem

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

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

Solution

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

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

Code Snippets

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

Context

Stack Overflow Q#48794974, score: 182

Revisions (0)

No revisions yet.