使用 println 将字符打印可变次数 [英] Printing a character a variable number of times with println
问题描述
我想使用println!
和format!
强大的格式化工具来打印一个字符特定的次数.当然,这可以通过循环实现,如下所示:
fn give_love(count: usize) {print!("这是对你的爱:");因为我在 0..count {打印!("♥");}println!("");}
但我既不想写循环也不想写三个print
.如何更短/更好地做到这一点?
代码的解决方案
fn give_love(count: usize) {println!("这是对你的爱:{:♥<1$}", "", count);}
<小时>
说明
您可以(错误地)使用填充功能,该功能允许使用您选择的某些字符填充打印值.仅此功能的语法如下所示:
'{' ':' <对齐><宽度>'}'
其中 width
是一个常数或对
.所以 3
表示宽度为常数 3,1$
表示 println!
的第一个参数的值的宽度.><小时>
然而:这里我们有点滥用"这个功能,我们不能忘记我们只是为其他一些可打印的东西指定填充",它通过参数传递给 println
.不过,这可以是一个空字符串.
println!("love: {:♥<3}", "");//爱:♥♥♥println!("爱:{:♥<1$}", "", 5);//爱:♥♥♥♥♥
以下是我们不传递空字符串的一些示例:
println!("love: {:♥<5}", "#");//爱:#♥♥♥♥println!("爱:{:♥>5}", "#");//爱:♥♥♥♥#println!("爱:{:♥^5}", "#");//爱:♥♥#♥♥
I want to use println!
and the powerful formatting tools of format!
to print a character a specific number of times. Of course this is possible with a loop, like so:
fn give_love(count: usize) {
print!("Here is love for you: ");
for i in 0..count {
print!("♥");
}
println!("");
}
But I neither want to write the loop nor the three print
s. How to do this shorter/better?
Solution to your code
fn give_love(count: usize) {
println!("Here is love for you: {:♥<1$}", "", count);
}
Explanation
You can (mis-)use the fill feature that allows to fill a printed value with some character of your choice. The grammar for this feature alone looks like:
'{' ':' <fill> <align> <width> '}'
Where width
is either a constant number or a reference to an argument of type <argument_index> '$'
. So 3
would mean a width of constant 3 and 1$
would mean a width of the value of the 1st argument of println!
.
However: here we are kind of "misusing" this feature and we mustn't forget that we are only specifying the "fill" for some other printable thing, which is passed by argument to println
. This can be an empty string though.
println!("love: {:♥<3}", ""); // love: ♥♥♥
println!("love: {:♥<1$}", "", 5); // love: ♥♥♥♥♥
Here are some examples where we don't pass an empty string:
println!("love: {:♥<5}", "#"); // love: #♥♥♥♥
println!("love: {:♥>5}", "#"); // love: ♥♥♥♥#
println!("love: {:♥^5}", "#"); // love: ♥♥#♥♥
这篇关于使用 println 将字符打印可变次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!