在保持上下文状态的情况下迭代字符串:
- 无
- 在一个".."
- 在一个(...)内
在上下文中,逗号没有分隔符的意思.
Limitations:这是一个午夜黑客!
另见Rust Playground
fn split(s: String) -> Vec<String> {
let mut context = 无;
let mut i = 0;
let mut start = 0;
let mut items = Vec::new();
for c in s.chars() {
if context == Some('"') {
if c == '"' {
context = 无;
}
i = i+1;
continue;
} else if context == Some('(') {
if c == ')' {
context = 无;
}
i = i+1;
continue;
}
if c == '"' || c == '(' {
context = Some(c);
}
if c == ',' && context.is_none() {
items.push(s[start..i].to_string());
start = i + 1;
}
i = i+1;
}
items.push(s[start..i].to_string());
items
}
fn main() {
let s = "something,\"in a string, oooh\",rgba(4,2,0)".to_string();
println!("{:?}", split(s));
// -> ["something", "\"in a string, oooh\"", "rgba(4,2,0)"]
}