Starts with. In Rust we can test the beginnings and ends of strings with starts_with and ends_with. Sometimes we may need to borrow from a String to get a str reference.
For some tests, we can take a slice of a string and compare it against a string literal. But starts_with and ends_with are usually easier to read.
An example. To begin, we create 2 strings with the String new() function and push_str. These are String objects, not str references. We call functions on the Strings.
Info These 2 functions receive str references (String slices). So we may need to borrow a String to get a str reference for the argument.
fn main() {
let mut data = String::new();
data.push_str("abcdef");
// Test with str reference argument directly.
if data.starts_with("abc") {
println!("STARTS WITH ABC");
}
let mut end = String::new();
end.push_str("def");
// Borrow the String to get a str reference.
if data.ends_with(&end) {
println!("ENDS WITH DEF");
}
}STARTS WITH ABC
ENDS WITH DEF
First char. We can take a slice of a string with a range index. And when we borrow the slice, we can compare it against a string literal.
Tip This syntax can perform the starts_with and ends_with logic, but the syntax is somewhat less clear.
However This syntax can test the inner part of a string by using a start and end offset to the range.
fn main() {
let mut data = String::new();
data.push_str("Cat");
// Test first letter of String.
if &data[0..1] == "C" {
println!("STARTS WITH C")
}
}STARTS WITH C
A summary. We reviewed some ways to test beginnings and ends of strings in Rust. We can use starts_with, ends_with, and even test string ranges with borrowing directly.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 30, 2022 (edit).