From 99077283baf722c6c36c35630d267fa6299fa935 Mon Sep 17 00:00:00 2001 From: Bauke Date: Thu, 7 Apr 2022 19:33:45 +0200 Subject: [PATCH] Solve length-of-last-word. --- source/length_of_last_word/mod.rs | 17 +++++++++++++++++ source/lib.rs | 1 + 2 files changed, 18 insertions(+) create mode 100644 source/length_of_last_word/mod.rs diff --git a/source/length_of_last_word/mod.rs b/source/length_of_last_word/mod.rs new file mode 100644 index 0000000..e30440c --- /dev/null +++ b/source/length_of_last_word/mod.rs @@ -0,0 +1,17 @@ +pub fn length_of_last_word(string: String) -> i32 { + string + .split_whitespace() + .last() + .map(|word| word.len()) + .unwrap_or_default() as i32 +} + +#[test] +fn test_length_of_last_word() { + assert_eq!(length_of_last_word("Hello World".to_string()), 5); + assert_eq!( + length_of_last_word(" fly me to the moon ".to_string()), + 4 + ); + assert_eq!(length_of_last_word("luffy is still joyboy".to_string()), 6); +} diff --git a/source/lib.rs b/source/lib.rs index be6e190..8194462 100644 --- a/source/lib.rs +++ b/source/lib.rs @@ -1,4 +1,5 @@ pub mod implement_strstr; +pub mod length_of_last_word; pub mod longest_common_prefix; pub mod palindrome_number; pub mod plus_one;