rust-book/slices/src/main.rs

45 lines
1.2 KiB
Rust

// Rust range syntax variants
// let len = s.len();
// &s[0..5] == &s[0..=4]
// &s[6..11] == &s[0..=10]
// &s[0..2] == &s[..2]
// &s[3..len] == &s[3..]
// &s[0..len] == &s[..]
fn main() {
let my_string = String::from("hello world");
// first_word works on slices of `String`s
let word = first_word(&my_string[..]);
println!("the first word is: {}", word);
let my_string_literal = "hello world";
// first_word works on slices of string literals
let word = first_word(&my_string_literal[..]);
println!("the first word is: {}", word);
// Because string literals *are* string slices already,
// this works too, without the slice syntax!
let word = first_word(my_string_literal);
println!("the first word is: {}", word);
}
// &str accepts both String and str, String type and slices
fn first_word(s: &str) -> &str {
let bytes = s.as_bytes(); // String to array of bytes
// enumerate takes the value of iter and returns a tuple for each index
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i]; // Return the slice from 0 to i-1
}
}
&s[..] // Return a slice equal to the input string
}