]> piware.de Git - learn-rust.git/blob - concepts/src/word_utils.rs
concepts: Add Post.reject() transition
[learn-rust.git] / concepts / src / word_utils.rs
1 pub fn first_word(s: &str) -> &str {
2     for (i, &item) in s.as_bytes().iter().enumerate() {
3         if item == b' ' {
4             return &s[..i];
5         }
6     }
7
8     s
9 }
10
11 pub fn second_word(s: &str) -> Option<&str> {
12     for (i, &item) in s.as_bytes().iter().enumerate() {
13         if item == b' ' {
14             return Some(first_word(&s[(i + 1)..]));
15         }
16     }
17
18     None
19 }
20
21 #[cfg(test)]
22 mod tests {
23     use super::*;
24
25     #[test]
26     fn test_first_word() {
27         assert_eq!(first_word(""), "");
28         assert_eq!(first_word("one"), "one");
29         assert_eq!(first_word("one two"), "one");
30
31         assert_eq!(first_word(&String::from("one two")), "one");
32     }
33
34     #[test]
35     fn test_second_word() {
36         assert_eq!(second_word(""), None);
37         assert_eq!(second_word("one"), None);
38         assert_eq!(second_word("one two"), Some("two"));
39         assert_eq!(second_word("one two three"), Some("two"));
40
41         assert_eq!(second_word(&String::from("one two three")), Some("two"));
42     }
43 }