英文:
How do I color a specific word in a string in Rust?
问题
我有一个Rust项目。
它的目的是接受两个参数,一个搜索词和一个文件名,然后将文件中包含搜索词的内容以红色打印出来。
我该如何实现这个功能?
以下是代码。
use std::env;
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::process;
fn main() {
let args: Vec<String> = env::args().collect();
let input_args: InputArgs = InputArgs::new(&args).unwrap_or_else(|err| {
println!("Problem parsing arguments: {}", err);
process::exit(1)
});
println!(
"Searching for {:?} in file {:?}.",
input_args.search_term, input_args.file_name
);
run(&input_args);
}
fn run(input_args: &InputArgs) -> io::Result<()> {
let file = File::open(&input_args.file_name)?;
let reader = io::BufReader::new(file);
for line in reader.lines() {
let line = line?;
println!("{}", line);
}
Ok(())
}
struct InputArgs {
search_term: String,
file_name: String,
}
impl InputArgs {
fn new(args: &[String]) -> Result<InputArgs, &str> {
if args.len() < 3 {
return Err("Please enter at least 2 arguments.");
}
let search_term: String = args[1].clone();
let file_name: String = args[2].clone();
return Ok(InputArgs {
search_term,
file_name,
});
}
}
我已经找到可以为整个字符串着色的库,但没有找到可以仅着色特定单词的库。
英文:
I have a Rust project.
It's purpose is to take 2 arguments, a search term and a file name, and print the contents of the file with the search term in the file colored red.
How do I achieve this?
Below is the code.
use std::env;
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::process;
fn main() {
let args: Vec<String> = env::args().collect();
let input_args: InputArgs = InputArgs::new(&args).unwrap_or_else(|err| {
println!("Problem parsing arguments: {}", err);
process::exit(1)
});
println!(
"Searching for {:?} in file {:?}.",
input_args.search_term, input_args.file_name
);
run(&input_args);
}
fn run(input_args: &InputArgs) -> io::Result<()> {
let file = File::open(&input_args.file_name)?;
let reader = io::BufReader::new(file);
for line in reader.lines() {
let line = line?;
println!("{}", line);
}
Ok(())
}
struct InputArgs {
search_term: String,
file_name: String,
}
impl InputArgs {
fn new(args: &[String]) -> Result<InputArgs, &str> {
if args.len() < 3 {
return Err("Please enter at least 2 arguments.");
}
let search_term: String = args[1].clone();
let file_name: String = args[2].clone();
return Ok(InputArgs {
search_term,
file_name,
});
}
}
I have found libraries that can color the entire string but not one that can color only specific words.
答案1
得分: 2
大多数能够给字符串上色的crate实际上都能够给单独的单词上色。例如,colored:
use colored::Colorize;
fn main() {
println!(
"{} {} {}",
"or use".cyan(),
"any".italic().yellow(),
"string type".cyan()
);
}
如果你想要构建一个字符串,也可以使用 format!
而不是 println!
来构建实际的字符串,而不是直接输出它,像这样:
use colored::Colorize;
fn main() {
let mut string = format!(
"{} {} {}",
"or use".cyan(),
"any".italic().yellow(),
"string type".cyan()
);
string.push_str(&"! hello".cyan().to_string());
println!("{string}");
}
英文:
Most of the crates that color a string actually are capable of coloring individual words. Take for example colored:
use colored::Colorize;
fn main() {
println!(
"{} {} {}",
"or use".cyan(),
"any".italic().yellow(),
"string type".cyan()
);
}
If you were trying to build a string, you could also use format!
instead of println!
to build the actual string instead of directly outputting it, like so:
use colored::Colorize;
fn main() {
let mut string = format!(
"{} {} {}",
"or use".cyan(),
"any".italic().yellow(),
"string type".cyan()
);
string.push_str(&*"! hello".cyan().to_string());
println!("{string}");
}
答案2
得分: 0
我已经找到了解决我的问题的方法。
以下是代码。
use colored::Colorize;
use std::env;
use std::fs;
fn main() {
let args: Vec<String> = env::args().collect();
let search_term: &str = &args[1];
let file_name: &str = &args[2];
println!(
"在文件 {} 中搜索项 {}。\n",
file_name.purple().italic(),
search_term.red().bold()
);
search_file(search_term, file_name)
}
fn search_file(search_term: &str, file_name: &str) -> () {
let content: String = fs::read_to_string(&file_name).expect("\n无法读取文件!");
for word in content.replace("\n", " \n").split(" ") {
if word.contains(search_term) {
print!("{} ", word.red().bold())
} else {
print!("{} ", word)
}
}
println!("")
}
希望这有所帮助!
英文:
I have found the solution to my problem.
Below is the code.
use colored::Colorize;
use std::env;
use std::fs;
fn main() {
let args: Vec<String> = env::args().collect();
let search_term: &str = &args[1];
let file_name: &str = &args[2];
println!(
"Searching for term {} in file {}.\n",
search_term.red().bold(),
file_name.purple().italic()
);
search_file(search_term, file_name)
}
fn search_file(search_term: &str, file_name: &str) -> () {
let content: String = fs::read_to_string(&file_name).expect("\nCould not read the file!");
for word in content.replace("\n", " \n").split(" ") {
if word.contains(search_term) {
print!("{} ", word.red().bold())
} else {
print!("{} ", word)
}
}
println!("")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论