]> piware.de Git - learn-rust.git/blob - src/main.rs
7a83cb487326028805912df69daa38a3c2cfa394
[learn-rust.git] / src / main.rs
1 mod word_utils {
2     pub fn first_word(s: &str) -> &str {
3         for (i, &item) in s.as_bytes().iter().enumerate() {
4             if item == b' ' {
5                 return &s[..i];
6             }
7         }
8
9         s
10     }
11
12     pub fn second_word(s: &str) -> Option<&str> {
13         for (i, &item) in s.as_bytes().iter().enumerate() {
14             if item == b' ' {
15                 return Some(first_word(&s[(i + 1)..]));
16             }
17         }
18
19         return None;
20     }
21 }
22
23 use word_utils::{first_word, second_word};
24
25 fn main() {
26     let s = String::from("Hello world");
27     println!("first word: '{}'", first_word(&s));
28     println!("second word: '{}'", second_word(&s).unwrap());
29
30     let s2 = "hello dude blah";
31     println!("second word of single: '{}'", second_word(s2).unwrap_or("(none)"));
32
33     match second_word(s2) {
34         Some(w) => println!("match: second word of '{}' exists: {}", s2, w),
35         None => println!("match: second word of '{}' does not exist", s2),
36     }
37 }