简体   繁体   English

如何在 rust 中将字符串拆分两次?

[英]How do i split a string twice in rust?

i need split String "fooo:3333#baaar:22222" Firstly by # secondary by:我需要拆分字符串“fooo:3333#baaar:22222”首先由#次要由:

and result must be <Vec<Vec<&str, i64>>>结果必须是 <Vec<Vec<&str, i64>>>
for the first step (split by #) i came up with第一步(由#分割)我想出了

.split('#').collect::<Vec<&str>>()  

but I can't think of a solution for the second step但我想不出第二步的解决方案

A Vec<&str, i64> is not a thing, so I assume u meant (&str, i64) Vec<&str, i64>不是一个东西,所以我假设你的意思是(&str, i64)

You can create that by splitting first, then mapping over the chunks.您可以通过先拆分然后映射块来创建它。

    let v = s
        .split('#') // split first time
        // "map" over the chunks and only take those where
        // the conversion to i64 worked
        .filter_map(|c| { 
            // split once returns an `Option<(&str, &str)>`
            c.split_once(':')
                // so we use `and_then` and return another `Option`
                // when the conversion worked (`.ok()` converts the `Result` to an `Option`)
                .and_then(|(l, r)| r.parse().ok().map(|r| (l, r)))
        })
        .collect::<Vec<(&str, i64)>>();

References:参考:
https://doc.rust-lang.org/std/primitive.str.html#method.split https://doc.rust-lang.org/std/primitive.str.html#method.split
https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.filter_map https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.filter_map
https://doc.rust-lang.org/core/primitive.str.html#method.split_once https://doc.rust-lang.org/core/primitive.str.html#method.split_once
https://doc.rust-lang.org/core/option/enum.Option.html#method.and_then https://doc.rust-lang.org/core/option/enum.Option.html#method.and_then
https://doc.rust-lang.org/std/primitive.str.html#method.parse https://doc.rust-lang.org/std/primitive.str.html#method.parse
https://doc.rust-lang.org/std/result/enum.Result.html#method.ok https://doc.rust-lang.org/std/result/enum.Result.html#method.ok

You can call a closure on each element of an iterator returned by the first split and split inside closure and push values to the vector.您可以对第一个拆分返回的迭代器的每个元素调用一个闭包,并在闭包内拆分并将值推送到向量。

    let mut out = Vec::new();
    s.split('#').for_each(|x| out.push(x.split(":").collect::<Vec<&str>>()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM