知识卡片
提取匹配查询的文本行
str::lines() 迭代原文本切片,contains(query) 判定子串匹配,命中时 push(line)。结果保留输入顺序。把该搜索函数保持为从文本到结果的转换,可直接构造字符串测试,文件和打印留给调用者。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- I/O 项目:构建命令行程序 Writing Code to Pass the Test · 查看原书依据
pub fn search<'a>( query: &str, contents: &'a str, ) -> Vec<&'a str> { let mut results = Vec::new(); for line in contents.lines() { if line.contains(query) { results.push(line); } } results }
参考来源
- 位置:《The Rust Programming Language(第2版)》第12章 I/O 项目:构建命令行程序(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c12.xhtml`,块 0227)
- 结论依据:完整示例用迭代、子串判断和向量收集连接每个步骤。
- 原始内容:pub fn search<'a>( query: &str, contents: &'a str, ) -> Vec<&'a str> { let mut results = Vec::new(); for line in contents.lines() { if line.contains(query) { results.push(line); } } results }