Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

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.

like image 355
John Doe Avatar asked Feb 14 '18 19:02

John Doe


People also ask

How do you check if a string is a substring of another Rust?

The easiest way to check if a Rust string contains a substring is to use String::contains method. The contains method Returns true if the given pattern matches a sub-slice of this string slice. The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

How do you test a substring?

You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1.

How do you parse a string in Rust?

To convert a string to an integer in Rust, use parse() function. The parse function needs to know what type, which can be specified on the left-side of assignment like so: let str = "123"; let num: i32 = str. parse().

How do you check if a string is a number Rust?

To check if a character is numeric in Rust, we use the is_numeric method. This method returns a Boolean, true or false depending on whether the character is numeric.


1 Answers

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

if a.contains("bc") {     do_something(); } 
like image 112
Kevin Hoerr Avatar answered Sep 24 '22 03:09

Kevin Hoerr