从文件中读取行,遍历每一行以及该行中的每个字符 [英] Read lines from file, iterate over each line and each character in that line

查看:154
本文介绍了从文件中读取行,遍历每一行以及该行中的每个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要读取一个文件,获取每一行,遍历每一行,并检查该行是否包含"aeiuo"中的任何字符,以及是否包含至少2个字符äüö".

I need to read a file, get each line, iterate over each line and check if that line contains any character from "aeiuo" and if it contains at least 2 of the characters "äüö".

此代码是Rust惯用的代码吗?如何检查String中的几个字符?

Is this code idiomatic Rust? How do I check for several characters in a String?

到目前为止,我的尝试是通过一些Google和代码窃取来完成的:

My attempt so far with some Google and code stealing:

use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
use std::path::Path;

fn main() {
    // Create a path to the desired file
    let path = Path::new("foo.txt");
    let display = path.display();

    // Open the path in read-only mode, returns `io::Result<File>`
    let file = match File::open(&path) {
        // The `description` method of `io::Error` returns a string that describes the error
        Err(why) => panic!("couldn't open {}: {}", display, Error::description(&why)),
        Ok(file) => file,
    };

    // Collect all lines into a vector
    let reader = BufReader::new(file);
    let lines: Vec<_> = reader.lines().collect();

    for l in lines {
        if (l.unwrap().contains("a")) {
            println!("here is a");
        }
    }
}

(游乐场链接)

推荐答案

这可行,

这篇关于从文件中读取行,遍历每一行以及该行中的每个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆