From 8f32bb41bae289264901a1e205ab38e12fcd8d56 Mon Sep 17 00:00:00 2001 From: Luke Tidd Date: Tue, 20 Dec 2022 09:14:10 -0500 Subject: [PATCH] finally finished slice... --- notes | 16 ++++++++++++++++ plants | 24 ++++++++++++++++++++++++ slice/src/main.rs | 22 +++++++++++++++++++--- 3 files changed, 59 insertions(+), 3 deletions(-) create mode 100644 plants diff --git a/notes b/notes index c6857be..16090f2 100644 --- a/notes +++ b/notes @@ -214,4 +214,20 @@ slices reference to a contiguous sequence of elements +enumerate returns a tuple with counter and reference to thing (counter, &thing) +slice is a pointer to a string, with a length + +let s = String::from("a a a a"); +slice = &s[0..2]; + +you can drop the first number if it's zero: let slice = &s[..2]; +or the last number if it's the end of the string: let slice = &s[4..]; +or both numbers to slice the whole thing: let slice = &s[..]; + +you can not create a slice that starts or ends within multibyte unicode parts + +String: a heap allocated vector of bytes that is stored on the heap. It is potentially mutable. +&str: an immutable borrowed string slice. + +let s = "string"; // string literal (it's a slice) diff --git a/plants b/plants new file mode 100644 index 0000000..6d17a63 --- /dev/null +++ b/plants @@ -0,0 +1,24 @@ +green shiso +green shiso +marvel of seasons +flower +parris island +rouge d'hiver +rouge d'hiver +flower +marvel of seasons +marvel of seasons +rouge d'hiver +flower +rouge d'hiver +parris island +black seeded simpson +flower +chives +black seeded simpson +dill +flower +red sails +genovese basil +deer tongue +48 flower diff --git a/slice/src/main.rs b/slice/src/main.rs index 38597ac..de08fcd 100644 --- a/slice/src/main.rs +++ b/slice/src/main.rs @@ -1,4 +1,4 @@ -fn first_word(s: &String) -> usize { +fn first_word_int(s: &str) -> usize { let b = s.as_bytes(); for (i, &val) in b.iter().enumerate() { if val == b' ' { @@ -7,7 +7,23 @@ fn first_word(s: &String) -> usize { } s.len() } -fn main() { - println!("{}", first_word(&String::from("sadf sdfsd fesf"))); +fn first_word(s: &str) -> &str { + let b = s.as_bytes(); + for (i, &val) in b.iter().enumerate() { + if val == b' ' { + return &s[..i]; + } + } + &s[..] +} +fn main() { + let test_string = "oh my gerd"; + let string = String::from("sdf sdf esv gs "); + let slice = &string[0..first_word_int(&string)]; + println!("here is the first word: _{}_", slice); + + println!("here is the first word: _{}_", first_word(&string)); + println!("here is the first word: _{}_", first_word(test_string)); + println!("{}", test_string); }