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.
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.
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
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.
starts_with
and ends_with
logic, but the syntax is somewhat less clear.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
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.