我需要读取一个文件,获取每一行,迭代每一行并检查该行是否包含“aeiuo”中的任何字符以及是否包含至少 2 个字符“äüö”。
这段代码是 Rust 惯用的吗?如何检查一个文件中是否有多个字符String
?
到目前为止,我在谷歌和代码窃取方面的尝试:
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");
}
}
}
(游乐场链接)
1)“这段代码是 Rust 惯用的吗?”
总体来说是的,看起来不错。您可能需要改进一个小点:您不需要将线收集到向量中以对其进行迭代。这是不需要的,因为它会触发不需要的内存分配。刚刚阅读lines()
迭代器直接就可以工作。 (如果您来自 C++,您可以忘记将事物收集到中间向量中:思考函数式,思考迭代器!)
let reader = BufReader::new(file);
let lines: Vec<_> = reader.lines().collect();
for l in lines {
...
}
becomes
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 {
...
}
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()
}
然后你可以一直使用迭代器并编写你的主要测试,如下所示:
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);
(完整代码位于操场.)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)