string - 为什么用彩色箱子中的彩色字符串替换子字符串不起作用?
问题描述
我正在尝试用彩色版本替换给定字符串的所有出现:
extern crate colored; // 1.6.1
use colored::Colorize;
fn print_found_line(x: &i32, line: &String, found: &str) {
let mut line_to_print: String = line.clone();
println!("{}", found.red()); // work
line_to_print = line_to_print.replace(found, found.red().as_ref());
println!("[{}] {}", x.to_string().blue(), line_to_print); // the found string replaced is not red
}
fn main() {}
第一个println!
按预期工作并以红色打印文本,但第二个println!
按预期工作并以默认颜色打印文本。
字符串文字似乎丢失了颜色信息。我想找到一个replace
可以打印我想要的文本的等价物。
解决方案
ColoredString
implements Deref<Target = str>
,但返回的&str
不包含任何颜色信息。您可以通过打印出取消引用的字符串来看到这一点:
println!("{}", found.red().as_ref() as &str);
看来正确的做法是将彩色文本转换为 aString
并将其用于格式化。
此外:
- 拿一个
&String
是没用的。 - 在替换之前克隆
String
它是没用的
fn print_found_line(x: &i32, line: &str, found: &str) {
let line_to_print = line.replace(found, &found.red().to_string());
println!("[{}] {}", x.to_string().blue(), line_to_print);
}
也可以看看:
推荐阅读
- swift - 检索最佳分数 Game Center Swift
- typescript - Cocos Creator 和 TypeScript 使用枚举作为属性
- php - 在蓝图中使用页面内容
- google-chrome - 创建 ChromeApps 仍然有意义吗?
- kivy - 无法使用 buildozer 从 kivy 创建 APK 文件
- python - 如何在 GTK (python 3, Gio) 应用程序中收听 DBus 信号?
- javascript - 如何使用 JSON 信息验证 Javascript 中的表单输入数据
- php - 如何在 laravel 中添加访客历史记录
- python - 如何绘制 XGBoost 评估指标?
- html - 不同平台上的 CSS 按钮