In Rust, checking if a string contains another string can be done using the contains method of the str type in the standard library. This is a simple and straightforward approach for verifying string containment.
How to Use the contains Method
The contains method takes a single parameter, which is the substring you want to check. It returns true if the main string contains this substring, and false otherwise.
Example Code
rustfn main() { let string = "Hello, world!"; let substring = "world"; let result = string.contains(substring); println!("Does the string contain the substring? {}", result); }
In this example, we check if "Hello, world!" contains the substring "world". The program outputs true because "world" is indeed a substring of "Hello, world!".
Important Notes
- The
containsmethod is case-sensitive, meaning that "hello" and "Hello" are treated as distinct strings. - For case-insensitive checks, you may need to convert both strings to lowercase (or uppercase) before invoking
contains.
rustfn main() { let string = "Hello, world!"; let substring = "World"; let result = string.to_lowercase().contains(&substring.to_lowercase()); println!("Does the string contain 'World' (case insensitive)? {}", result); }
Summary
Using the contains method is a direct and effective way to check for string containment in Rust. This approach works for most basic use cases and can be easily adapted to handle more complex requirements, such as case-insensitive checks.