Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a char to u32

Tags:

rust

As the questions states, how do I achieve this?

If I have a code like this:

let a = "29";
for c in a.chars() {
    println!("{}", c as u32);
}

What I obtain is the unicode codepoints for 2 and 9:

  • 50
  • 57

What I want is to parse those characters into the actual numbers.

like image 407
Dash83 Avatar asked Dec 29 '16 13:12

Dash83


People also ask

Can a char be a number C#?

IsNumber() is a C# method that is used to check whether a certain character or character in a string at a specified position is categorized as a number or not. If it is a number, then a Boolean True value is returned. If it is not a number, then a False value is returned.


1 Answers

char::to_digit(radix) does that. radix denotes the "base", i.e. 10 for the decimal system, 16 for hex, etc.:

let a = "29";
for c in a.chars() {
    println!("{:?}", c.to_digit(10));
}

It returns an Option, so you need to unwrap() it, or better: expect("that's no number!"). You can read more about proper error handling in the appropriate chapter of the Rust book.

like image 191
hansaplast Avatar answered Sep 23 '22 23:09

hansaplast