Rust 解析分隔文件中的变量

Rust 解析分隔文件中的变量,rust,Rust,我有一些文件内容是由管道符号分隔的。命名为,important.txt 然后,我使用Rust BufReader::split读取其内容 use std::error::Error; use std::fs::File; use std::io::BufReader; use std::io::Prelude::*; use std::path::Path; fn main() { let path = Path::new("important.txt"); let displ

我有一些文件内容是由管道符号分隔的。命名为,important.txt

然后,我使用Rust BufReader::split读取其内容

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

fn main() {
    let path = Path::new("important.txt");
    let display = path.display();

    //Open read-only
    let file = match File::open(&path) {
        Err(why) => panic!("can't open {}: {}", display,
                           Error::description(why)),
        Ok(file) => file,
    }

    //Read each line
    let reader = BufReader::new(&file);
    for vars in reader.split(b'|') {
        println!("{:?}\n", vars.unwrap());
    }
}
问题是,vars.unwrap将返回字节而不是字符串

[49]
[49, 51, 48]
[56, 48]
[49, 50, 48]
[49, 49, 48]
[69, 10, 50]
[50, 57, 48]
[52, 50, 48]
[57, 48]
[55, 48]
[66, 10, 51]
[49, 48, 48]
[50, 50, 48]
[51, 48]
[56, 48]
[67, 10]

您知道如何将此分隔文件解析为Rust中的变量吗?

由于您的数据是基于行的,您可以使用:

这将为输入中的每一行提供字符串迭代器。然后你用它来得到碎片

或者,您可以使用现有的&[u8]并使用以下命令生成字符串:


如果您正在读取结构化数据(如恰好以管道分隔的CSV),您可能还需要查看板条箱。

明白了。非常感谢你。
[49]
[49, 51, 48]
[56, 48]
[49, 50, 48]
[49, 49, 48]
[69, 10, 50]
[50, 57, 48]
[52, 50, 48]
[57, 48]
[55, 48]
[66, 10, 51]
[49, 48, 48]
[50, 50, 48]
[51, 48]
[56, 48]
[67, 10]
use std::io::{BufReader, BufRead};

fn main() {
    let input = r#"1|130|80|120|110|E
2|290|420|90|70|B
3|100|220|30|80|C
"#;

    let reader = BufReader::new(input.as_bytes());

    for line in reader.lines() {
        for value in line.unwrap().split('|') {
            println!("{}", value);
        }
    }
}
use std::io::{BufReader, BufRead};
use std::str;

fn main() {
    let input = r#"1|130|80|120|110|E
2|290|420|90|70|B
3|100|220|30|80|C
"#;

    let reader = BufReader::new(input.as_bytes());

    for vars in reader.split(b'|') {
        let bytes = vars.unwrap();
        let s = str::from_utf8(&bytes).unwrap();
        println!("{}", s);
    }
}