Home
Search
Rust starts with ExampleCall the starts with and ends with functions to test the beginnings and ends of strings.
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.
Substring
find
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.
Home
© 2007-2022 sam allen.
see site info on the changelog.