如何在Rust中将数字字符串转换为整数数组或整数向量? [英] How can I convert a string of numbers to an array or vector of integers in Rust?
本文介绍了如何在Rust中将数字字符串转换为整数数组或整数向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在STDIN上写了一个数字字符串(例如4 10 30 232312
),我想读取该数字并将其转换为整数数组(或向量),但是我找不到正确的方法.到目前为止,我有:
I'm writing on STDIN a string of numbers (e.g 4 10 30 232312
) and I want to read that and convert to an array (or a vector) of integers, but I can't find the right way. So far I have:
use std::io;
fn main() {
let mut reader = io::stdin();
let numbers = reader.read_line().unwrap();
}
推荐答案
在Rust 1.5.x上,有效的解决方案是:
On Rust 1.5.x, a working solution is:
fn main() {
let mut numbers = String::new();
io::stdin()
.read_line(&mut numbers)
.ok()
.expect("read error");
let numbers: Vec<i32> = numbers
.split_whitespace()
.map(|s| s.parse().expect("parse error"))
.collect();
for num in numbers {
println!("{}", num);
}
}
这篇关于如何在Rust中将数字字符串转换为整数数组或整数向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文