SpectraRust/src/math/count_words.rs
Asfmq 0674b4f174 feat: 添加 9 个 SYNSPEC 数学模块 (第8批)
新增模块:
- count_words: 字符串单词计数工具
- divhe2: He II Stark 轮廓除数参数计算
- extprf: 谱线轮廓波长外推 (Cooper 公式)
- feautr: Lyman-α Stark 加宽 (Feautrier 方法)
- gamhe: 中性氦 Stark 加宽参数
- griem: Griem Stark 阻尼参数计算
- intrp: 二分法高效插值程序
- partdv: 配分函数计算 (含压力效应)
- sffhmi_old: H- 自由-自由截面 (Kurucz 公式)

改进:
- 修复 fortran-analyzer 注释行误匹配问题

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-25 06:52:44 +08:00

94 lines
2.1 KiB
Rust

//! 字符串单词计数工具。
//!
//! 重构自 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<char> = 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);
}
}