]> piware.de Git - learn-rust.git/blobdiff - concepts/src/word_utils.rs
Move top-level files into concepts/
[learn-rust.git] / concepts / src / word_utils.rs
diff --git a/concepts/src/word_utils.rs b/concepts/src/word_utils.rs
new file mode 100644 (file)
index 0000000..e3e71bf
--- /dev/null
@@ -0,0 +1,43 @@
+pub fn first_word(s: &str) -> &str {
+    for (i, &item) in s.as_bytes().iter().enumerate() {
+        if item == b' ' {
+            return &s[..i];
+        }
+    }
+
+    s
+}
+
+pub fn second_word(s: &str) -> Option<&str> {
+    for (i, &item) in s.as_bytes().iter().enumerate() {
+        if item == b' ' {
+            return Some(first_word(&s[(i + 1)..]));
+        }
+    }
+
+    None
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_first_word() {
+        assert_eq!(first_word(""), "");
+        assert_eq!(first_word("one"), "one");
+        assert_eq!(first_word("one two"), "one");
+
+        assert_eq!(first_word(&String::from("one two")), "one");
+    }
+
+    #[test]
+    fn test_second_word() {
+        assert_eq!(second_word(""), None);
+        assert_eq!(second_word("one"), None);
+        assert_eq!(second_word("one two"), Some("two"));
+        assert_eq!(second_word("one two three"), Some("two"));
+
+        assert_eq!(second_word(&String::from("one two three")), Some("two"));
+    }
+}