MST

星途 面试题库

面试题:Rust字符串在文件读取中的应用

在Rust中,给定一个文本文件路径,使用Rust字符串相关方法,将文件内容读取出来,并统计文件中包含特定单词(比如“hello”)的行数。请写出实现该功能的代码。
26.1万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
use std::fs::File;
use std::io::{BufRead, BufReader};

fn main() {
    let file_path = "your_file_path.txt";
    let target_word = "hello";
    let mut count = 0;

    if let Ok(file) = File::open(file_path) {
        let reader = BufReader::new(file);
        for line in reader.lines() {
            if let Ok(text) = line {
                if text.contains(target_word) {
                    count += 1;
                }
            }
        }
    }

    println!("The number of lines containing '{}' is: {}", target_word, count);
}