//! 字符串单词计数工具。 //! //! 重构自 SYNSPEC `count_words.f` /// 统计字符串中由空格分隔的单词数量。 /// /// # 参数 /// /// * `cadena` - 输入字符串 /// /// # 返回值 /// /// 字符串中的单词数量 /// /// # 算法 /// /// 遍历字符串,当遇到非空格字符且前一个字符是空格时,计数加一。 /// 如果第一个字符不是空格,则计数从 1 开始。 /// /// # 示例 /// /// ``` /// use spectrarust::math::count_words::count_words; /// assert_eq!(count_words("hello world"), 2); /// assert_eq!(count_words(" hello world "), 2); /// assert_eq!(count_words(""), 0); /// assert_eq!(count_words(" "), 0); /// ``` pub fn count_words(cadena: &str) -> i32 { let chars: Vec = cadena.chars().collect(); let len = chars.len(); if len == 0 { return 0; } let mut n: i32 = 0; let mut a = chars[0]; // 如果第一个字符不是空格,计数从 1 开始 if a != ' ' { n = 1; } // 遍历剩余字符 for i in 1..len { let b = chars[i]; // 如果当前字符不是空格且前一个字符是空格,增加计数 if b != ' ' && a == ' ' { n += 1; } a = b; } n } #[cfg(test)] mod tests { use super::*; #[test] fn test_empty_string() { assert_eq!(count_words(""), 0); } #[test] fn test_only_spaces() { assert_eq!(count_words(" "), 0); } #[test] fn test_single_word() { assert_eq!(count_words("hello"), 1); assert_eq!(count_words(" hello"), 1); assert_eq!(count_words("hello "), 1); assert_eq!(count_words(" hello "), 1); } #[test] fn test_multiple_words() { assert_eq!(count_words("hello world"), 2); assert_eq!(count_words("hello world foo"), 3); assert_eq!(count_words(" hello world foo "), 3); } #[test] fn test_fortran_style() { // Fortran character*1000 测试 let long_str = "word1 word2 word3"; assert_eq!(count_words(long_str), 3); } }