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.
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.
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.
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().
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.
Rust has no such operator. You can use the String::contains
method instead:
if a.contains("bc") { do_something(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With