You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将向量格式字符串解析为Rust中的Vec<String>类型

在Rust中将特定格式字符串转为Vec的高效方法

针对你提供的字符串格式("['App01', 'App02', 'App03' , 'App04']"),最高效的方式是手动解析字符流,避免引入额外依赖或通用解析库的冗余开销。以下是具体实现:

fn parse_app_list(s: &str) -> Vec<String> {
    let mut result = Vec::new();
    let mut chars = s.chars().peekable();
    
    // 跳过开头的引号和左括号
    while let Some(&c) = chars.peek() {
        if c == '"' || c == '[' {
            chars.next();
        } else {
            break;
        }
    }
    
    let mut current = String::new();
    let mut in_quote = false;
    
    while let Some(c) = chars.next() {
        match c {
            // 遇到单引号时切换引号包裹状态
            '\'' => {
                if in_quote {
                    // 结束包裹,将当前收集的字符串存入结果
                    result.push(current);
                    current = String::new();
                }
                in_quote = !in_quote;
            }
            // 非包裹状态下,跳过逗号、空格、右括号和结尾引号
            ',' | ' ' | ']' | '"' if !in_quote => continue,
            // 包裹状态下,收集字符到当前字符串
            _ if in_quote => current.push(c),
            _ => continue,
        }
    }
    
    result
}

fn main() {
    let input = "\"['App01', 'App02', 'App03' , 'App04']\"";
    let apps = parse_app_list(input);
    println!("{:?}", apps); // 输出 ["App01", "App02", "App03", "App04"]
}

为什么这是最高效的?

  • 仅做一次字符遍历,无额外的字符串分割、正则匹配等操作
  • 内存分配最小:只为每个App名称分配一次String空间
  • 无外部依赖,编译体积更小,运行时开销更低

如果追求代码简洁性,可以接受轻微性能损耗的话,也可以用regex库快速提取:

use regex::Regex;

fn parse_with_regex(s: &str) -> Vec<String> {
    let re = Regex::new(r"'([^']+)'").unwrap();
    re.captures_iter(s)
        .map(|cap| cap[1].to_string())
        .collect()
}

若你的字符串格式可能扩展为标准JSON(比如改用双引号),可以用serde_json处理,但会引入更大依赖,性能也不如手动解析:

use serde_json::Value;

fn parse_with_serde(s: &str) -> Vec<String> {
    // 替换单引号为双引号,转为标准JSON格式
    let json_str = s.replace('\'', '"');
    let value: Value = serde_json::from_str(&json_str).unwrap();
    value.as_array().unwrap()
        .iter()
        .map(|v| v.as_str().unwrap().to_string())
        .collect()
}

内容的提问来源于stack exchange,提问作者h1990

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 17:25:19