pub fn first_word_func() {
let mut s = String::from("hello world");
let word = first_word_no_slice(&s); s.clear();
}
fn first_word_no_slice(s: &String) -> usize {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return i;
}
}
s.len()
}
pub fn slices() {
let s = String::from("hello world");
let hello = &s[0..5];
println!("hello: {}", hello);
let world = &s[6..11];
println!("world: {}", world);
let s = String::from("hello");
let slice = &s[0..2];
println!("slice: {}", slice);
let slice = &s[..2];
println!("slice: {}", slice);
let s = String::from("hello");
let len = s.len();
let slice = &s[3..len];
println!("slice: {}", slice);
let slice = &s[3..];
println!("slice: {}", slice);
let s = String::from("hello");
let len = s.len();
let slice = &s[0..len];
println!("slice: {}", slice);
let slice = &s[..];
println!("slice: {}", slice);
}
pub fn first_word_slice() {
let mut s = String::from("hello world");
let word = first_word(&s);
println!("the first word is: {}", word);
let my_string = String::from("hello world");
let word = first_word(&my_string[0..6]);
let word = first_word(&my_string[..]);
let word = first_word(&my_string);
let my_string_literal = "hello world";
let word = first_word(&my_string_literal[0..6]);
let word = first_word(&my_string_literal[..]);
let word = first_word(my_string_literal);
}
pub 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[..]
}
pub fn array_slices() {
let a = [1, 2, 3, 4, 5];
let slice = &a[1..3];
assert_eq!(slice, &[2, 3]);
}