MST

星途 面试题库

面试题:Rust中如何遍历字符串并统计特定字符的数量

在Rust中,给定一个字符串,例如 `let s = "hello world";`,请编写代码遍历该字符串,统计其中字母 `l` 出现的次数,并返回这个统计结果。
25.4万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
fn count_l(s: &str) -> u32 {
    s.chars().filter(|c| *c == 'l').count() as u32
}

你可以这样调用这个函数:

fn main() {
    let s = "hello world";
    let count = count_l(s);
    println!("字母 'l' 出现的次数: {}", count);
}