[英]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.