Home > Net >  Break the command line argument string by four or any such number in Rust
Break the command line argument string by four or any such number in Rust

Time:06-18

Currently for example I take an command line argument in rust

use std::env;

fn main()
{
    let args: Vec<String> = env::args().collect();
    let arg_string: String = args[1..].join(" ");
    let arg_length: u8 = args.len().try_into().unwrap();
    println!("{}", arg_string);
}

the output will be

$ ./target/debug/_program_name_ Testing the args to work
Testing the args to work

so this allows me to print all the command line args after ./program_name, but I would like the output to be like

$ ./target/debug/_program_name_ Testing the args to work
Testing the args to
work

another example

$ ./target/debug/_program_name_ Something here to show to stackoverflow
Something here to show
to stackoverflow

I tried doing this

use std::env;

fn main()
{
    let args: Vec<String> = env::args().collect();
    let arg_string: String;
    let arg_length: u8 = args.len().try_into().unwrap();

    let mut arg_mod_four: u8 = ((arg_length % 4)   4 ) % 4;
    let mut array_string: [&str; (arg_mod_four   1)]
    for i in 0..arg_mod_four
    {
        arg_string[i] = args[(4 * i   1)..(4(i   1))].join(" ");
    
    array_string[arg_mod_four   1] = args[(arg_mod_four * 4   1)..arg_length].join(" ")
    for j in 0..(arg_mod_four   1)
    {
        println!("{}", &arg_string[j]);
    }
}

but there are several errors here and I would not want to use this (nor does it work).

CodePudding user response:

You can use the chunks method of a slice:

let args: Vec<String> = env::args().skip(1).collect();

for chunk in args.chunks(4) {
    println!("{}", chunk.join(" "));
}

The method isn't defined on iterators, so we call .collect() first to get a slice. You could probably use itertools instead, but for command-line parsing I wouldn't bother to optimize.

CodePudding user response:

like this?

use std::env;

fn main() {
    let args: Vec<String> = env::args().collect();
    for (i, arg) in args[1..].iter().enumerate() {
        match (i   1) % 4 {
            0 => println!("{}", arg),
            _ => print!("{}", arg),
        }
    }
}
  • Related