fun with string slices
This commit is contained in:
parent
e5b04eb8c4
commit
8266d81352
@ -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[..]
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user