rust 如何有效地进行字符串匹配?

rjzwgtxy  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(125)

我有这样一段代码,它可以执行强力搜索来查找字符串的匹配项:

fn main() {
    let strings: Vec<String> = ["a", "b", "c","d","e","f","g","h","i","j","K","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"].map(String::from).to_vec();
    for i in strings.iter(){
        for j in strings.iter(){
            for k in strings.iter(){
                for l in strings.iter(){
                    let mut result = format!("{i}{j}{k}{l}");
                    println!("{}",result);
                    if result == "Kaio"{
                        println!("Found it!!");
                        return ;
                    }
                }
            }
        }
    }
}

有没有更好的方法呢?我可以动态地做吗?在这个例子中,我使用了四个循环,假设最后一个字符串的长度是4。但是如果有一个动态大小的字符串,我不知道它的大小呢?

rxztt3cl

rxztt3cl1#

itertools crate提供了一个很好的宏来在iproduct中生成此宏。

use itertools::iproduct;

fn main() {
    let pool: Vec<String> = "abcdefghijklmnopqrstuvwxyz".chars().map(String::from).collect();
    let possibilities: Vec<String> = iproduct!(&pool, &pool, &pool, &pool)  // for four-letters
        .map(|(a, b, c, d)| format!("{}{}{}{}", a, b, c, d))
        .collect();

    for password in possibilities {
        if password == "eggs" {
            println!("We found it!");
        }
    }
}

相关问题