乐闻世界logo
搜索文章和话题

How to convert a Rust char to an integer so that ' 1 ' becomes 1?

1个答案

1

In Rust, converting the character '1' to the integer 1 can be achieved using the to_digit method, which is part of the char type. This method accepts a radix parameter; for decimal conversion, the radix must be 10.

Here is a simple example:

rust
fn main() { let c = '1'; if let Some(num) = c.to_digit(10) { println!("Character '{}' corresponds to integer {}", c, num); } else { println!("Character '{}' cannot be converted to an integer.", c); } }

In this example:

  1. A variable named c is created that holds the character '1'.
  2. c.to_digit(10) is used to attempt converting the character to an Option<u32> integer, where 10 is the radix (since we are converting decimal digits).
  3. The to_digit method returns an Option<u32>, containing Some(value) on successful conversion and None if the character is not a valid digit.
  4. The if let construct is employed to check the result of to_digit and handle it accordingly.

The to_digit method is highly versatile, as it supports conversions for digits beyond decimal (e.g., hexadecimal or octal) by simply adjusting the radix value passed to it.

Another approach involves directly computing the difference between the char value and the character '0' to obtain the equivalent numeric value. For example:

rust
fn main() { let c = '1'; let num = c as u32 - '0' as u32; println!("Character '{}' corresponds to integer {}", c, num); }

Here, the character '1' and '0' are explicitly converted to u32 and their difference is calculated to derive the corresponding integer. This method is limited to ASCII characters and assumes the character represents a digit between 0 and 9.

2024年6月29日 12:07 回复

你的答案