< 返回版块

eksea 发表于 2021-02-04 17:36

Tags:iterator

背景:实现strtol的rust版本

代码:

fn strtol(chars: &mut Chars<'_>) -> i64 {
    let mut result: i64 = 0;
    loop {
        match chars.next() {
            Some(c) => {
                match c.to_digit(10) {
                    Some(i) => result = result * 10 + i64::from(i),
                    None => break,
                }
            },
            None => break,
        }
    }
    result
}

问题:执行完函数后,迭代器指向的字符是数字后面的第二个字符;例如输入123abc,运行后,迭代器指向字符b,我想要的结果是指向字符a,这样,可以继续用该迭代器进行后续操作。

评论区

写评论
作者 eksea 2021-02-05 10:40

Peekable正是我想要的,多谢

--
👇
ywxt:

use core::str::Chars;

fn strtol(chars: &mut Chars<'_>) -> i64 {
    let mut result: i64 = 0;
    let mut chars = chars.peekable();
    loop {
        match chars.peek() {
            Some(c) => {
                match c.to_digit(10) {
                    Some(i) => {
                        result = result * 10 + i64::from(i);
                        chars.next();
                    }
                    None => break,
                }
            }
            None => break,
        }
    }
    println!("{:?}", chars.peek());
    result
}

fn main() {
    println!("{}", strtol(&mut "123abc".chars()));
}
93996817 2021-02-05 09:21
//只能想到这个方法
use core::str::Chars;
fn strtol(chars: &mut Chars<'_>) -> i64 {
    let mut result: i64 = 0;
    let mut c1 = chars.clone();
    loop {
        match chars.next() {
            Some(c) => match c.to_digit(10) {
                Some(i) => {
                    result = result * 10 + i64::from(i);
                    c1.next();
                }
                None => {
                    *chars = c1;
                    break;
                }
            },
            None => break,
        }
    }
    result
}

fn main() {
    let mut data = "123abc".chars();
    println!("result={}", strtol(&mut data));
    println!("next={:?}", data.next());
    /* TomRust
     Running `target\debug\test001.exe`
     result=123
     next=Some('a')
    */
}
ywxt 2021-02-04 23:15
use core::str::Chars;

fn strtol(chars: &mut Chars<'_>) -> i64 {
    let mut result: i64 = 0;
    let mut chars = chars.peekable();
    loop {
        match chars.peek() {
            Some(c) => {
                match c.to_digit(10) {
                    Some(i) => {
                        result = result * 10 + i64::from(i);
                        chars.next();
                    }
                    None => break,
                }
            }
            None => break,
        }
    }
    println!("{:?}", chars.peek());
    result
}

fn main() {
    println!("{}", strtol(&mut "123abc".chars()));
}
1 共 3 条评论, 1 页