什么是最简单的方法来填充左侧的0的字符串? [英] What is the easiest way to pad a string with 0 to the left?
问题描述
最简单的方法是在左侧填充0的字符串,这样
What is the easiest way to pad a string with 0 to the left so that
-
"110" ="00000110"
"110" = "00000110"
"11110000" ="11110000"
"11110000" = "11110000"
我尝试使用format!
宏,但它仅向右填充空格:
I have tried to use the format!
macro but it only pads to the right with space:
format!("{:08}", string);
推荐答案
fmt
模块文档描述了所有格式选项:
The fmt
module documentation describes all the formatting options:
填充/对齐
通常将填充字符与
width
参数.这表示如果要格式化的值是 小于width
的地方,将会在其周围打印一些额外的字符. 多余的字符由fill
指定,对齐方式可以是 以下选项之一:
Fill / Alignment
The fill character is provided normally in conjunction with the
width
parameter. This indicates that if the value being formatted is smaller thanwidth
some extra characters will be printed around it. The extra characters are specified byfill
, and the alignment can be one of the following options:
-
<
-参数在width
列中左对齐 -
^
-参数在width
列中居中对齐 -
>
-参数在width
列中右对齐
<
- the argument is left-aligned inwidth
columns^
- the argument is center-aligned inwidth
columns>
- the argument is right-aligned inwidth
columns
assert_eq!("00000110", format!("{:0>8}", "110"));
// |||
// ||+-- width
// |+--- align
// +---- fill
另请参阅:
- How can I 0-pad a number by a variable amount when formatting with std::fmt?
- How do I print an integer in binary with leading zeros?
- Hexadecimal formating with padded zeroes
- Convert binary string to hex string with leading zeroes in Rust
这篇关于什么是最简单的方法来填充左侧的0的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!