fun with string slices

This commit is contained in:
Dan Buch 2017-12-30 21:56:46 -05:00
parent e5b04eb8c4
commit 8266d81352
Signed by: meatballhat
GPG Key ID: 9685130D8B763EA7

View File

@ -1,18 +1,26 @@
fn main() {
let s = String::from("what the what");
let w = first_word(&s);
let s = String::from("hello world");
println!("w={}", w);
let word = first_word(&s[..]);
println!("word={}", word);
let l = "hello world";
let word = first_word(&l[..]);
println!("word={}", word);
let word = first_word(l);
println!("word={}", word);
}
fn first_word(s: &String) -> usize {
fn first_word(s: &str) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return i;
return &s[0..i];
}
}
s.len()
&s[..]
}