Question

I'd like to iterate through a sentence to extract out simple words from the string. Here's what I have so far, trying to make the parse function first match world in the input string:

fn parse(input: String) -> String {
    let mut val = String::new();

    for c in input.chars() {
        if c == "w".to_string() {
            // guessing I have to test one character at a time
            val.push_str(c.to_str());
        }
    }

    return val;
}

fn main() {
    let s = "Hello world!".to_string();
    println!("{}", parse(s)); // should say "world"
}

What is the correct way to iterate through the characters in a string to match patterns in Rust (such as for a basic parser)?

Was it helpful?

Solution

Checking for words in a string is easy with the str::contains method.

As for writing a parser itself, I don't think it's any different in Rust than other languages. You have to create some sort of state machine.

For examples, you could check out serialize::json. I also wrote a CSV parser that uses a buffer with a convenient read_char method. The advantage of using this approach is that you don't need to load the whole input into memory at once.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top