rust - 如何在文本文件或变量中查找关键字?
问题描述
我想在文本文件或变量中查找关键字。我想获取用户输入并将其粘贴到文本文件中。
我的代码:
use std::fs;
fn main() {
let mut user_name = String::new();
println!("Hello what is your name: ");
std::io::stdin().read_line(&mut name).unwrap();
fs::write("files/user_name.txt", user_name).unwrap();
let mut user_wish = String::new();
println!("What is your wish: ");
std::io::stdin().read_line(&mut user_wish).unwrap();
fs::write("files/user_wish.txt", user_wish).unwrap();
}
我不知道如何在文本文件user_wish.txtmy
中找到和之类的关键字,以便列出.name
user_name
解决方案
use std::fs;
static KEYWORDS: &'static [&'static str] = &["my", "name"];
fn main() {
let mut user_name = String::new();
println!("Hello what is your name: ");
std::io::stdin().read_line(&mut user_name).unwrap();
// ---
// fs::write<P, C>(path: P, contents: C)
// -- Note contents takes ownership of `C` / `user_clone`
// that memory will be consumed after it finishes
// so we give it clone(), so we can still access `user_name`
fs::write("files/user_name.txt", user_name.clone()).unwrap();
for kword in KEYWORDS {
if user_name.contains(kword) {
println!("contains keyword");
}
}
let mut user_wish = String::new();
println!("What is your wish: ");
std::io::stdin().read_line(&mut user_wish).unwrap();
fs::write("files/user_wish.txt", user_wish).unwrap();
}
推荐阅读
- bash - [已解决] execl("/bin/bash", ...) 的不可预知的行为
- excel - 使用 Dateif 公式求和
- javascript - Frida 将对象转换为字符串列表
- python-3.x - 是否可以参数化由点表示法调用的方法?
- mysql - 最近版本中 Python 的字符串格式化程序更改是否破坏了 MySQL 连接器?
- javascript - 在 Vue.js 组件之间共享功能?
- arrays - 访问键:[ {“Key”:“Value”}] 在另一个数组中的对象内部?
- python - 将网页部署到 github,其中 html 文件位于模板文件夹中
- php - Laravel 8 从 AWS S3 存储桶下载文件
- c++ - NetUserChangePassword() 可以给管理员设置密码吗?