【发布时间】:2015-08-27 17:32:03
【问题描述】:
我需要读取一个文件,获取每一行,遍历每一行并检查该行是否包含“aeiuo”中的任何字符以及是否包含至少 2 个字符“äüö”。
这段代码是惯用的 Rust 吗?如何检查 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");
}
}
}
【问题讨论】:
-
这听起来像是两个问题:“我的代码是否好/惯用”和“如何在字符串中查找多个字符”。这些应该分开;后者对于 Stack Overflow 来说是个好问题,但第一个问题应该提交给 Code Review - 确保遵守他们的提交规则!那里需要工作代码。
-
我同意@Shepmaster 但我想回答这个问题:pastebin.com/6uSBrFzQ
-
谢谢,我会用这个改进我的代码:)。
标签: loops character line rust contains