h1990
h1990

Reputation: 165

How to parse string containing vectors to actual vector

I have a string that I'm reading from input stream:

"['App01', 'App02', 'App03' , 'App04']"

What's the most efficient way to convert it to a Vec<String> type in Rust?

Upvotes: 0

Views: 102

Answers (2)

cafce25
cafce25

Reputation: 27357

As a Code Golf answer:

serde_json::from_str(&s.replace('\'', "\"")).unwrap()

But both replace and from_str have to copy the strings data so memory wise it's probably not the best.

Upvotes: 2

rburmorrison
rburmorrison

Reputation: 730

There's a lot of ways to parse a string like this, and it depends what you mean by "efficent" (performance? lines of code?), but here's a possible solution:

fn main() {
    let input = "['App01', 'App02', 'App03' , 'App04']";

    // Start by removing the surrounding braces.
    let trimmed = input.trim_matches(['[', ']'].as_slice());

    // Make the vector by:
    let vector: Vec<String> = trimmed
        .split(',') // separating the string parts by the comma
        .map(str::trim) // cleaning each part by removing surrounding space
        .map(|item| item.trim_matches('\'')) // then removing the single quotes
        .map(String::from) // and converting each item from a slice to an owned String
        .collect(); // and putting it all into a vector

    println!("{vector:#?}");
}

And its output:

[
    "App01",
    "App02",
    "App03",
    "App04",
]

That's assuming you truly want an owned String. But it'd be a bit better if you opted to use a reference instead. To do that, it'd look like this instead:

let vector: Vec<&str> = trimmed
    .split(',') // separating the string parts by the comma
    .map(str::trim) // cleaning each part by removing surrounding space
    .map(|item| item.trim_matches('\'')) // then removing the single quotes
    .collect(); // and putting it all into a vector

Notice that the .map(String::from) call is gone and the resulting type is Vec<&str>. This avoids duplicating the strings and instead just uses a reference to the original input, using less memory overall.

Hope this helps.

Upvotes: 1

Related Questions