从文件中读取行,迭代每一行和该行中的每个字符

Veg*_*ega 3 loops contains character line rust

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

这段代码是 Rust 惯用的吗?如何检查 a 中的多个字符String?

到目前为止,我尝试了一些 Google 和代码窃取:

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::to_string(&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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

(游乐场链接)

mdu*_*dup 5

1) “这段代码是 Rust 惯用的吗?”

总的来说是的,看起来不错。您可能希望改进一个小点:您不需要将这些行收集到一个向量中来对其进行迭代。这是不需要的,因为它会触发不需要的内存分配。lines()直接读取迭代器就可以了。(如果你来自 C++,你可以忘记将东西收集到中间向量中:想想函数式,想想迭代器!)

let reader = BufReader::new(file);
let lines: Vec<_> = reader.lines().collect();

for l in lines {
    ...
}
Run Code Online (Sandbox Code Playgroud)

变成

let reader = BufReader::new(file);
let lines = reader.lines(); 
// lines is a instance of some type which implements Iterator<Item=&str>

for l in lines {
    ...
}
Run Code Online (Sandbox Code Playgroud)

2)“如何检查字符串中的多个字符?”

我建议一个简单的方法基于.any():

fn is_aeiou(x: &char) -> bool {
    "aeiou".chars().any(|y| y == *x)
}

fn is_weird_auo(x: &char) -> bool {
    "äüö".chars().any(|y| y == *x)
}

fn valid(line: &str) -> bool {
    line.chars().any(|c| is_aeiou(&c)) &&
    line.chars().filter(is_weird_auo).fuse().nth(1).is_some()
}
Run Code Online (Sandbox Code Playgroud)

然后你可以一直使用迭代器并按如下方式编写主要测试:

let reader = BufReader::new(file);
let lines = reader.lines();

let bad_line = lines.map(|l| l.unwrap()).filter(|line| !valid(line)).next();
match bad_line {
    Some(line_n) => println!("Line {} doesn't pass the test", line_n),
    None => println!("All lines are good!"),
}

// Alternate way if you don't need the line number. More readable
//let all_good = lines.map(|l| l.unwrap()).all(valid);
Run Code Online (Sandbox Code Playgroud)

(操场上的完整代码。)

  • 这个解决方案是不正确的:它不会处理“äüö”:那些是使用多个代码点的*分解*形式。在进行比较时,您应该规范化输入,并且应该使用 `graphemes` 迭代器**而不是**`chars` 迭代器(为此,您需要 crates.io 中的 `unicode-segmentation` 包,除非您想使用夜间和不稳定的功能)。 (2认同)
  • @Vega:不幸的是,这不是一件容易的事,因为 Unicode 很复杂。我建议在 [维基百科](http://en.wikipedia.org/wiki/Unicode) 上阅读关于 *code points*、*graphemes*、*combining character sequences* 的内容,你会明白你的 `String` 可能相当复杂的。至于显示字符串的问题,您确定您的终端已正确配置为显示UTF-8吗? (2认同)