How can I convert a string of numbers to an array or vector of integers in Rust?

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();
}

You can do something like this:

use std::io::{self, BufRead};                   // (a)

fn main() {
    let reader = io::stdin();
    let numbers: Vec<i32> = 
        reader.lock()                           // (0)
              .lines().next().unwrap().unwrap() // (1)
              .split(' ').map(|s| s.trim())     // (2)
              .filter(|s| !s.is_empty())        // (3)
              .map(|s| s.parse().unwrap())      // (4)
              .collect();                       // (5)
    println!("{:?}", numbers);
}

First, we take a lock of the stdin which lets you work with stdin as a buffered reader. By default, stdin in Rust is unbuffered; you need to call the lock() method to obtain a buffered version of it, but this buffered version is the only one for all threads in your program, hence the access to it should be synchronized.

Next, we read the next line (1); I'm using the lines() iterator whose next() method returns Option<io::Result<String>>, therefore to obtain just String you need to unwrap() twice.

Then we split it by spaces and trim resulting chunks from extra whitespace (2), remove empty chunks which were left after trimming (3), convert strings to i32s (4) and collect the result to a vector (5).

We also need to import std::io::BufRead trait (a) in order to use the lines() method.

If you know in advance that your input won't contain more than one space between numbers, you can omit step (3) and move the trim() call from (2) to (1):

let numbers: Vec<i32> = 
    reader.lock()
          .lines().next().unwrap().unwrap()
          .trim().split(' ')
          .map(|s| s.parse().unwrap())
          .collect();

Rust also provides a method to split a string into a sequence of whitespace-separated words, called split_whitespace():

let numbers: Vec<i32> =
    reader.read_line().unwrap().as_slice()
        .split_whitespace()
        .map(|s| s.parse().unwrap())
        .collect()

split_whitespace() is in fact just a combination of split() and filter(), just like in my original example. It uses a split() function argument which checks for different kinds of whitespace, not only space characters.

Convert a String of numbers to an Array/Vector of ints in Rust, 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 of int (or a vector) in Rust, can't find the right way ,� Rust struct &str and String. You may be wondering why we need to_string(). Rust has two main types of strings: &str and String. &str is called ‘string slices’. A string slice has a fixed size, and cannot be mutated. A String is stored as a vector. String is heap-allocated, growable, and not null

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);
    }
}

How can I convert a string of numbers to an array or , I'm writing on STDIN a string of numbers (e.g 4 10 30 232312) and I want to How can I convert a string of numbers to an array or vector of integers in Rust? Each signed variant can store numbers from -(2 n - 1) to 2 n - 1 - 1 inclusive, where n is the number of bits that variant uses. So an i8 can store numbers from -(2 7) to 2 7 - 1, which equals -128 to 127. Unsigned variants can store numbers from 0 to 2 n - 1, so a u8 can store numbers from 0 to 2 8 - 1, which equals 0 to 255.

Safer version. This one skips failed parses so that failed unwrap doesn't panic. Use read_line for reading single line.

let mut buf = String::new();

// use read_line for reading single line 
std::io::stdin().read_to_string(&mut buf).expect("");

// this one skips failed parses so that failed unwrap doesn't panic
let v: Vec<i32> = buf
    .split_whitespace() // split string into words by whitespace
    .filter_map(|w| w.parse().ok()) // calling ok() turns Result to Option so that filter_map can discard None values
    .collect(); // collect items into Vector. This determined by type annotation.

You can even read Vector of Vectors like this.

let stdin = io::stdin();
let locked = stdin.lock();
let vv: Vec<Vec<i32>> = locked.lines()
    .filter_map(
        |l| l.ok().map(
            |s| s.split_whitespace()
                 .filter_map(|word| word.parse().ok())
                 .collect()))
    .collect();

Above one works for inputs like

2 424 -42 124
42 242 23 22 241
24 12 3 232 445

then turns them it into

[[2, 424, -42, 124],
[42, 242, 23, 22, 241],
[24, 12, 3, 232, 445]]

filter_map accepts a closure that returns Option<T> and filters out all Nones.

ok() turns Result<R,E> to Option<R> so that errors can be filtered in this case.

How to convert a vector of strings into numbers, You can change the existing Rpn_string into an Rpn_numbers , and declare it as a vector of 32-bit integers (or whatever kind of number you� If s is a string matrix, return a column vector with one converted number per row of s; Invalid rows evaluate to NaN. If s is a cell array of strings, return a column vector with one converted number per cell element in s. See also: dec2bin, base2dec, hex2dec. : dec2bin (d, len)

How do I convert Vec of i32 to string - help, I have a vector of i32 values. How do I convert Vec of i32 to string � help of type `i32` cannot be built from an iterator over elements of type `{integer}` | So are you trying to make a Vec<String> of the individual numbers? A UTF-8 encoded, growable string. The String type is the most common string type that has ownership over the contents of the string. It has a close relationship with its borrowed counterpart, the primitive str. Examples. You can create a String from a literal string with String::from:

Rust cheat sheet, �. 22. Convert string to integer. Extract integer value i from its string representation s (� Create an empty array with size as string length and initialize all of the elements of array to zero. Start traversing the string. Check if the character at the current index in the string is a comma (,). If yes then, increment the index of the array to point to the next element of array.

Rust Cookbook � A Guide to Porting C and C++ code to Rust, Let's say you have an integer you want to turn into a string. +. In C++ you [https ://doc.rust-lang.org/std/fmt/] for this purpose and it is similar to printf / sprintf: + Unlike an array which has a fixed length, a vector can grow or shrink over time. +. std::string s("123"); int i; std::from_chars(s.data(), s.data() + s.size(), i, 10);

Comments
  • Thank you Vladimir, you saved the day. On a side note, wow, Rust is really intense!
  • There is also a way to use regular expressions to split by arbitrary whitespaces. It probably would give terser code, but it requires using non-standard crates (although it is included into the distribution). The example here is almost what you want.
  • You can also just use .words() (slightly more general than just spaces, though).
  • Yes, somehow I missed it. It still is a combination of split() and filter(), as it follows from the type :)
  • @VladimirMatveev what would the be the best way to achieve this in today's Rust version? I've been trying to get the pieces together online but seems that the information available is not up to date. Thank you :)