diff options
Diffstat (limited to 'rust/theBook/chapter-4-understanding-ownership/str.rs')
-rw-r--r-- | rust/theBook/chapter-4-understanding-ownership/str.rs | 38 |
1 files changed, 38 insertions, 0 deletions
diff --git a/rust/theBook/chapter-4-understanding-ownership/str.rs b/rust/theBook/chapter-4-understanding-ownership/str.rs new file mode 100644 index 0000000..09bab67 --- /dev/null +++ b/rust/theBook/chapter-4-understanding-ownership/str.rs @@ -0,0 +1,38 @@ +fn first_word(s: &String) -> usize { + let bytes = s.as_bytes(); + + for (i, &item) in bytes.iter().enumerate() { + if item == b' ' { + return i; + } + } + + s.len() +} + +fn second_word(s: &str) -> &str { + let bytes = s.as_bytes(); + + for (i, &item) in bytes.iter().enumerate() { + if item == b' ' { + return &s[0..i]; + } + } + + &s[0..s.len()] +} + +fn main() { + let mut s = String::from("hello world"); + + let word = first_word(&s); + + println!("{word}"); + + println!("{}",&s[0..5]); + + let word2 = second_word(&s[..]); + + println!("{}",&word2); + s.clear(); +} |