Pet*_*mit 15 string parsing rust
我需要在每一行解析一个文件
<string><space><int><space><float>
Run Code Online (Sandbox Code Playgroud)
例如
abce 2 2.5
Run Code Online (Sandbox Code Playgroud)
在CI中会做:
scanf("%s%d%f", &s, &i, &f);
Run Code Online (Sandbox Code Playgroud)
如何在Rust中轻松地和惯用地执行此操作?
A.B*_*.B. 17
标准库不提供此功能.你可以用宏编写自己的.
macro_rules! scan {
( $string:expr, $sep:expr, $( $x:ty ),+ ) => {{
let mut iter = $string.split($sep);
($(iter.next().and_then(|word| word.parse::<$x>().ok()),)*)
}}
}
fn main() {
let output = scan!("2 false fox", char::is_whitespace, u8, bool, String);
println!("{:?}", output); // (Some(2), Some(false), Some("fox"))
}
Run Code Online (Sandbox Code Playgroud)
宏的第二个输入参数可以是&str,char或适当的闭包/函数.指定的类型必须实现FromStr特征.
请注意,我将它快速放在一起,因此未经过彻底测试.
oli*_*obk 10
您可以使用text_iocrate进行类似scanf的输入,以便print!在语法中模仿宏
#[macro_use] extern crate text_io;
fn main() {
// note that the whitespace between the {} is relevant
// placing any characters there will ignore them but require
// the input to have them
let (s, i, j): (String, i32, f32);
scan!("{} {} {}\n", s, i, j);
}
Run Code Online (Sandbox Code Playgroud)
您还可以将其分为3个命令:
#[macro_use] extern crate text_io;
fn main() {
let a: String = read!("{} ");
let b: i32 = read!("{} ");
let c: f32 = read!("{}\n");
}
Run Code Online (Sandbox Code Playgroud)
该scan_fmt箱提供了另一种选择。它支持简单的模式,在选项中返回它的输出,并且有一个我觉得更适合text_io的语法:
#[macro_use] extern crate scan_fmt;
fn main() {
let (s, i, j) = scan_fmt!("abce 2 2.5", "{} {d} {f}\n", String, i32, f32);
println!("{} {} {}", s.unwrap(), i.unwrap(), j.unwrap());
}
Run Code Online (Sandbox Code Playgroud)