summaryrefslogtreecommitdiff
path: root/rust/theBook/chapter-4-understanding-ownership/str.rs
diff options
context:
space:
mode:
authorgarhve <git@garhve.com>2022-12-26 16:52:29 +0800
committergarhve <git@garhve.com>2022-12-26 16:52:29 +0800
commit3172b239863e1151d85197fdb4ea3e42d421256e (patch)
tree81e4eb4eb06725f17188bf85d9cd7305eceedab3 /rust/theBook/chapter-4-understanding-ownership/str.rs
parent1dece36fd7e315aee98f1c06d7064fbd6ef877e8 (diff)
finish chapter 5
Diffstat (limited to 'rust/theBook/chapter-4-understanding-ownership/str.rs')
-rw-r--r--rust/theBook/chapter-4-understanding-ownership/str.rs38
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();
+}