HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustCritical

How do I split a string in Rust?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
stringhowsplitrust

Problem

From the documentation, it's not clear. In Java you could use the split method like so:

"some string 123 ffd".split("123");

Solution

Use split()

let parts = "some string 123 content".split("123");


This gives an iterator, which you can loop over, or collect() into a vector. For example:

for part in parts {
    println!("{}", part)
}


Or:

let collection = parts.collect::>();
dbg!(collection);


Or:

let collection: Vec = parts.collect();
dbg!(collection);

Code Snippets

let parts = "some string 123 content".split("123");
for part in parts {
    println!("{}", part)
}
let collection = parts.collect::<Vec<&str>>();
dbg!(collection);
let collection: Vec<&str> = parts.collect();
dbg!(collection);

Context

Stack Overflow Q#26643688, score: 469

Revisions (0)

No revisions yet.