如何使用字符串迭代器执行前瞻?

问题描述 投票:0回答:1

我想尝试熟悉 Rust,所以我正在尝试使用 Rust Crafting Interpreters。目前,在 Longer Lexemes 部分,它有一个

peek
函数,它可以获取当前索引前面的字符。

我不知道如何在 Rust 中解决这个问题。由于语言的设计和 Unicode 的复杂性,似乎不鼓励索引字符串。

如果我这样做

chars.next()
那么它将消耗该值。我认为原始字符串上的
.as_bytes()
可以工作,但只支持 ASCII 值。从网上看,
.chars().nth().unwrap()
是解决方案,但是好像很慢。

string rust iterator
1个回答
0
投票

@BallpointBen 评论的一个实际例子是:

fn main() {
    let data = "Hello, world!";
    let mut iter = data.chars().peekable();
    
    while let Some(&current) = iter.peek() {
        // Do something with the current character without consuming it
        println!("Current character: {}", current);

        // Now consume the character
        iter.next();
        
        // You can also peek the next character without consuming it
        if let Some(&next) = iter.peek() {
            println!("Next character: {}", next);
        } else {
            println!("This was the last character.");
        }
    }
}

Rust Playground 示例

输出:

Current character: H
Next character: e
Current character: e
Next character: l
Current character: l
Next character: l
Current character: l
Next character: o
Current character: o
Next character: ,
Current character: ,
Next character:  
Current character:  
Next character: w
Current character: w
Next character: o
Current character: o
Next character: r
Current character: r
Next character: l
Current character: l
Next character: d
Current character: d
Next character: !
© www.soinside.com 2019 - 2024. All rights reserved.