Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter all non-integers from string and yield vector

Tags:

rust

I have an Into<String> variable called t_num. I'm attempting to filter all non-integers from the string and return a Vec<usize> containing a vector of all integers in the string. Here's my attempt:

     let filter_vec = t_num.into().chars().
         filter(|a| a.parse::<usize>()).                                                                                      
         collect::<Vec<_>>();

The problem is i'm getting the error

error: no method named `parse` found for type `&char` in the current scope
       filter(|a| a.parse::<usize>()).

so the problem is that char doesn't implement parse, is there a method similar to parse implemented for char?

like image 722
Syntactic Fructose Avatar asked Oct 27 '25 05:10

Syntactic Fructose


1 Answers

char has a to_digit method that converts a character to the corresponding digit.

fn parse_digits(t_num: &str) -> Vec<u32> {
    t_num
        .chars()
        .filter_map(|a| a.to_digit(10))
        .collect()
}

fn main() {
    println!("{:?}", parse_digits("123asd456")); // prints [1, 2, 3, 4, 5, 6]
}
like image 102
Francis Gagné Avatar answered Oct 30 '25 08:10

Francis Gagné