How to index a string vector

In C, I define char **argv and could use argv[i][j] or *(*(argv+i)+j). But how to do this in Rust?
I known that I can use as_bytes() in string, but this works only in 1D array I guess.

for example
let argv: Vec<String> = env::argv().collect();
How can I get argv[i][j] ?

Thanks a lot.

You could do something like this:

fn main() {
    let argv: Vec<Vec<u8>> = std::env::args().map(|single_string| {
        single_string.as_bytes().to_vec()
    }).collect();

    println!("{}", argv[0][0]);
}

This works for me

fn main() {
    let args: Vec<_> = std::env::args().collect();
    println!("{}", args[0].as_bytes()[0]);
}

That's unnecessarily expensive. Why take the owned strings, get their underlying slice, and then copy the whole thing with an extra allocation for each?

If one already has a Vec<String>, the following works:

let argv: Vec<String> = env::args().collect();
let byte_i_j = argv[i].as_bytes()[j];

However, this is probably not what OP wants.

@moon548834, am I guessing right that you are trying to parse the command line arguments? Be aware that string bytes aren't equivalent to "characters" because Rust supports Unicode and Strings are always encoded as UTF-8. Depending on your definition of a "character", you might be looking for str::chars() (which gives you Unicode code points) or UnicodeSegmentation::graphemes() (this one gives you grapheme clusters), neither of which can possibly provide random access indexing, because UTF-8 and Unicode in general are variable-length encodings at multiple levels.

TL;DR: If you just want to parse command-line arguments easily, check out some dedicated crates such as structopt, docopt, clap, getopts (for a less sophisticated but more traditional alternative), or some of the several other command line utility crates.

3 Likes

thanks.

It works, and you're right, I'm trying to parse the command line arguments. I will look through these crates soon.

If it's just being used to parse command args, the extra expense is ultimately negligible. But yeah, your method and @alice 's method is more sound under any context. Thanks for the tip!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.