Add string slicing example
This commit is contained in:
parent
30649df52e
commit
6c3d7f50ce
2 changed files with 27 additions and 0 deletions
18
string_slicing/src/main.rs
Normal file
18
string_slicing/src/main.rs
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
fn first_word(s: &String) -> &str {
|
||||
let bytes = s.as_bytes();
|
||||
|
||||
for (i, &item) in bytes.iter().enumerate() {
|
||||
if item == b' ' {
|
||||
return &s[..i]
|
||||
}
|
||||
}
|
||||
|
||||
&s[..]
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let s = String::from("Hello world");
|
||||
|
||||
println!("String: {}", s);
|
||||
println!("First word: {}", first_word(&s));
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue