简体   繁体   English

我们如何在特定分隔符之前连接向量元素并在 Rust 中创建新向量

[英]How can we Concatenate vector elements before specific separator and make new vector in Rust

I want to to concatenate all 3 elements of vector named 'items' before operator and two elements after operator like this ["2","2","2","+","2","3"] to ["222","+","23"]我想将运算符之前名为“items”的向量的所有 3 个元素和运算符之后的两个元素连接起来,像这样 ["2","2","2","+","2","3"] 到 [ "222","+","23"]

let items = vec!["2","2","2","+","2","3"];
let mut new_items = vec![];
for i in 0..items.len() {
    new_items.insert(i, items[i].to_owned());
}
let mut count = 0;
for i in 0..new_items.len() {
    if new_items[i] == "+" {}
    else {            
        new_items[i] = format!("{}{}",new_items[i],new_items[i+1]);
        new_items.remove(i+1);
        count += 1;
    }
}

println!("{:?}",new_items);

Maybe something like the following:也许类似于以下内容:

pub fn main() {
    let items = vec!["2","2","2","+","2","3"];

    // use a number variable to capture the operand
    let mut number = String::new();
    let mut new_items = vec![];

    for s in items {
        if s == "+" {
            // if found an operator, push and clear the current operand and operator
            new_items.push(number.drain(..).collect());
            new_items.push(s.to_owned());
        } else {
            number.push_str(s);
        }
    }

    if !number.is_empty() {
        new_items.push(number);
    }

    println!("{:?}", new_items);
}

the playground . 操场

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

相关问题 如何连接 Rust Vector 的两个 `&str` 类型元素并添加到零索引 - How can I concatenate two `&str` type elements of Rust Vector and add to Zero Index 将字符向量中元素的唯一组合连接到 R 中的新字符串向量中 - Concatenate unique combinations of elements in a character vector into new vector of strings in R 如何将整数向量的元素连接到 C++ 中的字符串? - How can I concatenate the elements of a vector of integers to a string in C++? 如何在 Rust 中将字符串转换为向量? - How can I convert a String into a Vector in Rust? 如何用字符串向量的元素替换向量的特定元素? - How to replace specific elements of a vector with elements of a string vector? 如何在 rust 中返回字符串向量 - How to return a vector of strings in rust 用Rust中的向量元素替换编号的占位符? - Replacing numbered placeholders with elements of a vector in Rust? 如何在 Rust 中将一串数字转换为整数数组或向量? - How can I convert a string of numbers to an array or vector of integers in Rust? 如何实现对向量的元素顺序添加,在插入之前对其进行排序? - How to realize sequent addition of elements to vector, sorting them before to insert? 如何在 Rust 中加入一个字符向量 - How do I join a char vector in Rust
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM