Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through characters in a string in Rust to match words?

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)?

like image 890
Lance Avatar asked Mar 29 '14 22:03

Lance


1 Answers

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.

like image 79
BurntSushi5 Avatar answered Sep 30 '22 19:09

BurntSushi5