Split With Char Arrays And Closures

str::split accepts char arrays and closures as patterns, so mixed / and \ separators tokenize in one pass without pre-normalizing.

RustData Integrity

Code

rustsnippet
16 lines
fn main() {
    // mixed / and \ separators: char arrays split both in one pass
    let mixed = "/var/log//app\\logs\\audit.log";
    let parts: Vec<&str> = mixed.split(['/', '\\']).filter(|p| !p.is_empty()).collect();
    println!("{parts:?}");
    println!("components: {}", parts.len());

    // reassemble with one canonical separator
    println!("normalized: /{}", parts.join("/"));

    // closures are patterns too: comma or semicolon both split
    let row = "id,name;role,dept;city";
    let fields: Vec<&str> = row.split(|c: char| c == ',' || c == ';').collect();
    println!("{fields:?}");
    println!("field count: {}", fields.len());
}

Inside the snippet

The code’s whole job belongs to the function main.

What to watch for

  • Built-in APIs only — no supply chain needs to be vetted.

Putting it to use

The primary signature, spelled out, is fn main()

The file’s output announces each step as it happens: components:, normalized: /, field count:.

The core lines, annotated

let parts: Vec<&str> = mixed.split(['/', '\\']).filter(|p| !p.is_empty()).collect();
let fields: Vec<&str> = row.split(|c: char| c == ',' || c == ';').collect();

Interactive Tools for This Topic

FAQ

What does Split With Char Arrays And Closures print when run?
The script runs standalone; its 3 labeled outputs include `components:`, `normalized: /`, `field count:`.