[英]Rust: access line in file by index, or is there another way to compare two lines
i have a simple txt file with one value per line.我有一个简单的 txt 文件,每行一个值。 Is it somehow possible to compare two lines?
是否有可能比较两条线?
I was looking for a way to index each line and then compare the index [n] with index [n+1].我正在寻找一种方法来索引每一行,然后将索引 [n] 与索引 [n+1] 进行比较。 By now i am able to print each line, but not to compare the entries.
现在我可以打印每一行,但不能比较条目。
Here is my code:这是我的代码:
use std::fs::File;
use std::env;
use std::io::{self, BufReader, BufRead};
fn read_file(filename: &String) -> io::Result<()> {
let file = File::open(filename)?;
let content = BufReader::new(file);
for line in content.lines() {
println!("{}", line.unwrap());
}
Ok(())
}
fn main() {
let args: Vec<String> = env::args().collect();
let filename = &args[1];
read_file(filename).expect("error reading file");
}
One solution is to collect all lines into a vector and use std::iter::zip
function .一种解决方案是将所有行收集到一个向量中并使用
std::iter::zip
function 。
fn read_file(filename: &String) -> io::Result<()> {
let file = File::open(filename)?;
let content = BufReader::new(file);
let lines: Vec<String> = content
.lines()
.map(|line| line.expect("Something went wrong"))
.collect();
for (current, next) in lines.iter().zip(lines.iter().skip(1)) {
println!("{}, {}", current, next)
}
Ok(())
}
So for the input file having content,所以对于有内容的输入文件,
1
2
3
4
read_file
function will print read_file
function 将打印
1, 2
2, 3
3, 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.