Use the contains() method on the &str type to check for a substring, which returns a boolean. For case-insensitive checks, convert both strings to lowercase before comparing or use the regex crate for more complex patterns.
Here is the standard approach using the built-in contains() method:
fn main() {
let text = "Rust is a systems programming language";
let search_term = "systems";
if text.contains(search_term) {
println!("Found: {}", search_term);
} else {
println!("Not found");
}
// Case-insensitive check
let has_rust = text.to_lowercase().contains("rust");
println!("Contains 'rust' (case-insensitive): {}", has_rust);
}
If you need to check for multiple substrings or require regex support, the regex crate is the standard tool. It handles Unicode boundaries and complex patterns better than manual string manipulation.
// Add to Cargo.toml: regex = "1"
use regex::Regex;
fn main() {
let text = "Contact us at support@example.com or sales@example.com";
let re = Regex::new(r"@example\.com").unwrap();
if re.is_match(text) {
println!("Email domain found");
}
}
The contains() method is efficient for simple ASCII or Unicode substring checks and is available on all string slices (&str) and owned strings (String). It handles Unicode scalars correctly, so searching for characters like "é" or emojis works as expected without extra configuration. For performance-critical loops, ensure you are borrowing (&str) rather than cloning strings, as contains() does not require ownership.