首页 > 解决方案 > 如何在文本文件或变量中查找关键字?

问题描述

我想在文本文件或变量中查找关键字。我想获取用户输入并将其粘贴到文本文件中。

我的代码:

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中找到和之类的关键字,以便列出.nameuser_name

标签: rust

解决方案


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();
}

推荐阅读