Use the .as_bytes() method to convert a string to a byte slice for efficient character searching.
Use the .as_bytes() method on a &String or &str to get a byte slice, then iterate over it to find specific byte values like spaces.
fn first_word(s: &str) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}
&s[..]
}
The bytes crate in Rust converts a text string into a list of raw numbers representing each character so you can search for them efficiently. It is like turning a sentence into a barcode to find a specific pattern without reading the whole word. You use this when you need to locate a character, like a space, to split text.