summaryrefslogtreecommitdiff
path: root/rust/chap4/slice_me.rs
diff options
context:
space:
mode:
Diffstat (limited to 'rust/chap4/slice_me.rs')
-rw-r--r--rust/chap4/slice_me.rs26
1 files changed, 26 insertions, 0 deletions
diff --git a/rust/chap4/slice_me.rs b/rust/chap4/slice_me.rs
new file mode 100644
index 0000000..da201a1
--- /dev/null
+++ b/rust/chap4/slice_me.rs
@@ -0,0 +1,26 @@
+
+/* Return the index of the first space or s.len()*/
+fn get_word_index(s: &str) -> usize {
+ let bytes = s.as_bytes();
+
+ for (i, &item) in bytes.iter().enumerate() {
+ if item == b' ' {
+ return i;
+ }
+ }
+
+ return s.len();
+}
+
+fn first_word(s: &str) -> &str {
+ let idx = get_word_index(s);
+
+ return &s[..idx];
+}
+
+fn main() {
+ let s = String::from("corno manso ronaldo curintiano");
+ let slice = first_word(&s);
+
+ println!("{slice}");
+}