如何在 Rust 中将一串数字转换为整数数组或向量? [英] How can I convert a string of numbers to an array or vector of integers in Rust?

查看:38
本文介绍了如何在 Rust 中将一串数字转换为整数数组或向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 STDIN 上写了一串数字(例如 4 10 30 232312),我想读取它并转换为整数数组(或向量),但我不能t 找到正确的方法.到目前为止,我有:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆