You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust程序问题:如何打印子串匹配的行内容及位置

Rust程序问题:匹配子串时无法打印行内容

你遇到的错误根源是:line 是 Result<String, std::io::Error> 类型,默认格式化器无法直接处理该类型;同时你之前仅通过 line.unwrap() 临时取出字符串但未保存,导致后续无法复用行内容。

修复方案

先将 line 解析为字符串并保存,再用该字符串执行查找和打印操作:

use std::{
    fs::File,
    io::{BufRead, BufReader},
};

fn read_file_line(filepath: &String) -> BufReader<File> {
    let data = File::open(filepath).unwrap();
    BufReader::new(data)
}

fn main() {
    let filepath = "src/poem.txt".to_string();
    let filecontents = read_file_line(&filepath);
    let search_phrase = "article".to_string();

    for line in filecontents.lines() {
        // 解析Result并保存行字符串
        let line_str = line.unwrap();
        // 使用保存的字符串执行查找
        let index = line_str.find(&search_phrase.trim());

        match index {
            Some(t) => println!("Found at position {t} of the line: {line_str}"),
            None => (),
        }
    }
}

额外优化建议

直接使用 unwrap() 会在IO错误时崩溃,建议用错误处理逻辑让程序更健壮:

for line in filecontents.lines() {
    match line {
        Ok(line_str) => {
            if let Some(t) = line_str.find(&search_phrase.trim()) {
                println!("Found at position {t} of the line: {line_str}");
            }
        }
        Err(e) => eprintln!("Failed to read line: {e}"),
    }
}

内容的提问来源于stack exchange,提问作者yolo_ML

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 05:10:35