【问题标题】:How to convert a string of digits into a vector of digits?如何将一串数字转换为数字向量?
【发布时间】:2017-09-16 21:36:38
【问题描述】:

我正在尝试存储数字的string(或str),例如将12345 转化为一个向量,使得该向量包含{1,2,3,4,5}

由于我是 Rust 的新手,我遇到了类型问题(Stringstrchar,...),而且缺少任何关于转换的信息。

我当前的代码如下所示:

fn main() {
    let text = "731671";                
    let mut v: Vec<i32>;
    let mut d = text.chars();
    for i in 0..text.len() {
        v.push( d.next().to_digit(10) );
    }
}

【问题讨论】:

标签: string char rust type-conversion


【解决方案1】:

你已经接近了!

首先,索引循环for i in 0..text.len() 不是必需的,因为无论如何您都将使用迭代器。直接在迭代器上循环更简单:for ch in text.chars()。不仅如此,您的索引循环和字符迭代器很可能会发生分歧,因为len() 返回字节数,chars() 返回Unicode 标量值。作为 UTF-8,字符串的 Unicode 标量值可能比它的字节数少。

下一个障碍是to_digit(10) 返回一个Option,告诉您该字符有可能不是数字。您可以检查to_digit(10) 是否返回了OptionSome 变体if let Some(digit) = ch.to_digit(10)

拼凑起来,代码现在可能如下所示:

fn main() {
    let text = "731671";
    let mut v = Vec::new();
    for ch in text.chars() {
        if let Some(digit) = ch.to_digit(10) {
            v.push(digit);
        }
    }
    println!("{:?}", v);
}

现在,这是相当必要的:您要自己制作一个向量并逐位填充它。您可以通过对字符串应用转换来尝试更多 declarative or functional 方法:

fn main() {
    let text = "731671";
    let v: Vec<u32> = text.chars().flat_map(|ch| ch.to_digit(10)).collect();
    println!("{:?}", v);
}

【讨论】:

    【解决方案2】:

    ArtemGr 的回答很好,但他们的版本会跳过任何不是数字的字符。如果你宁愿让它在错误的数字上失败,你可以改用这个版本:

    fn to_digits(text: &str) -> Option<Vec<u32>> {
        text.chars().map(|ch| ch.to_digit(10)).collect()
    }
    fn main() {
        println!("{:?}", to_digits("731671"));
        println!("{:?}", to_digits("731six71"));
    }
    

    输出:

    Some([7, 3, 1, 6, 7, 1])
    None
    

    【讨论】:

      【解决方案3】:

      Rust 的新版本

      如果转换为数字失败,则返回一个枚举。

      #[derive(Debug, PartialEq)]
      pub enum Error {
          InvalidDigit(char),
      }
      
      
      fn to_digits(text: &str) ->  Result<Vec<u32>, Error> {
      
          let mut numbers = Vec::new();
          for s in string_digits.chars(){
      
              match s.to_digit(10){
                  Some(number) => numbers.push(number),
                  None => {return Err(Error::InvalidDigit(s));}
              }
          Ok(numbers)
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-06
        • 2021-09-19
        • 2013-03-18
        • 2014-12-19
        • 2016-05-03
        • 2011-10-31
        • 2019-10-26
        相关资源
        最近更新 更多