How to split a string into words in Rust

2 Answers

0 votes
use regex::Regex;
 
fn split_string<'a>(s: &'a str, delims: &str) -> Vec<&'a str> {
    let re = Regex::new(delims).expect("Invalid regex");
    re.split(s)
        .filter(|t| !t.is_empty())
        .collect()
}
 
fn main() {
    let s = "-c, c++.. c#:: -java ,php...python   rust";
    let delims = r"[ ,.:\-!]+";
 
    let tokens = split_string(s, delims);
 
    for t in tokens {
        println!("{}", t);
    }
}
 
 
/*
run:
 
c
c++
c#
java
php
python
rust
 
*/

 



answered Aug 29 by avibootz
0 votes
use std::collections::HashSet;

fn split_string(s: &str, delims: &str) -> Vec<String> {
    let delim_set: HashSet<char> = delims.chars().collect();

    let normalized: String = s
        .chars()
        .map(|ch| if delim_set.contains(&ch) { ' ' } else { ch })
        .collect();

    normalized
        .split_whitespace()
        .map(|t| t.to_string())
        .collect()
}

fn main() {
    let s: &str = "-c, c++.. c#:: -java! ,php...python:      rust!";
    let delims: &str = " ,.:\\-!";

    let tokens: Vec<String> = split_string(s, delims);

    for t in tokens {
        println!("{}", t);
    }
}


/*
run:

c
c++
c#
java
php
python
rust

*/

 



answered Aug 29 by avibootz
...