Strings and Text Processing
contains() and starts_with()
The .contains(), .starts_with(), and .ends_with() methods on str test whether a string slice matches a given pattern (&str, char, &[char], or a char predicate closure) and return a bool.
Signatures and Supported Patterns
pub fn contains<P: Pattern>(&self, pat: P) -> bool
pub fn starts_with<P: Pattern>(&self, pat: P) -> bool
pub fn ends_with<P: Pattern>(&self, pat: P) -> bool
Pattern Type P |
Example Call | What It Tests |
|---|---|---|
&str |
s.starts_with("https://") |
Exact substring match |
char |
s.ends_with('/') |
Single character match (faster than 1-char "/" literal) |
&[char] |
s.starts_with(&['#', ';'][..]) |
Matches any character in the slice |
FnMut(char) -> bool |
s.contains(char::is_numeric) |
Matches any character satisfying the predicate |
Testing Prefixes, Suffixes, and Substrings
fn main() {
let url = "https://crates.io/crates/serde";
println!("Is HTTPS: {}", url.starts_with("https://"));
println!("Ends with serde: {}", url.ends_with("/serde"));
println!("Contains crates: {}", url.contains("crates"));
// Using a char predicate closure:
let password = " correct-horse-9 ";
println!("Has digit: {}", password.contains(|c: char| c.is_ascii_digit()));
println!("Has whitespace: {}", password.contains(char::is_whitespace));
}
Is HTTPS: true
Ends with serde: true
Contains crates: true
Has digit: true
Has whitespace: true
Case-Insensitive ASCII Matching (eq_ignore_ascii_case)
When comparing strings or prefixes case-insensitively for ASCII protocols (such as HTTP headers or SQL keywords), use s.eq_ignore_ascii_case(other) rather than allocating a new lowercase String via .to_lowercase():
fn is_bearer_token(header_value: &str) -> bool {
header_value
.get(..7)
.is_some_and(|prefix| prefix.eq_ignore_ascii_case("bearer "))
}
fn main() {
println!("'Bearer xyz': {}", is_bearer_token("Bearer xyz"));
println!("'BEARER xyz': {}", is_bearer_token("BEARER xyz"));
println!("'Basic xyz': {}", is_bearer_token("Basic xyz"));
}
'Bearer xyz': true
'BEARER xyz': true
'Basic xyz': false