简体   繁体   English

如何遍历Rust中字符串中的字符来匹配单词?

[英]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: 这是我到目前为止所做的,尝试使输入字符串中的parse函数首先匹配world

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)? 迭代字符串中的字符以匹配Rust中的模式(例如基本解析器)的正确方法是什么?

Checking for words in a string is easy with the str::contains method. 使用str::contains方法可以轻松检查字符串中的单词。

As for writing a parser itself, I don't think it's any different in Rust than other languages. 至于编写解析器本身,我认为它与Rust在其他语言上没有任何不同。 You have to create some sort of state machine. 你必须创建某种状态机。

For examples, you could check out serialize::json . 例如,您可以查看serialize::json I also wrote a CSV parser that uses a buffer with a convenient read_char method. 我还编写了一个CSV解析器 ,它使用带有方便的read_char方法的缓冲区。 The advantage of using this approach is that you don't need to load the whole input into memory at once. 使用此方法的优点是您不需要立即将整个输入加载到内存中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 字符串匹配:单词+字符 - string match: words + characters 你如何将一个长字符串分解成单词并遍历单词的每个字符,如果它们匹配使用 stringstream 增加一个字符计数 - How do you break a long string into words and iterate through each character of word and if they match increment a char count using stringstream 如何根据以下字符/单词匹配URI字符串的特定部分 - How to match specific part of the URI string based on the following characters / words 如何遍历字符串向量中每个字符串中的字符? - How to iterate through characters in each string in a vector of strings? 如何遍历字符串并在某些字符后连接 - How to iterate through string and concatenate after certain characters 给定字符串,如何遍历许多正则表达式以找到匹配项? - Given a string, how to iterate through many regexes to find a match? 如何遍历NSString的字符 - How to iterate through the characters of an NSString 遍历字符串中的字符并删除连续的重复项 - Iterate through characters in a string and remove consecutive duplicates 遍历字符串字符以删除块引用 - Iterate through string characters to remove blockquotes 如何在Rust中匹配字符串与字符串? - How to match String against String in Rust?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM