简体   繁体   中英

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"]

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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