[英]What is the easiest way to pad a string with 0 to the left?
What is the easiest way to pad a string with 0 to the left so that用 0 向左填充字符串的最简单方法是什么,以便
"110" = "00000110" “110”=“00000110”
"11110000" = "11110000" “11110000”=“11110000”
I have tried to use the format!
我试过用format!
macro but it only pads to the right with space:宏,但它只在右侧填充空格:
format!("{:08}", string);
The fmt
module documentation describes all the formatting options: fmt
模块文档描述了所有格式选项:
Fill / Alignment填充/对齐
The fill character is provided normally in conjunction with the
width
parameter.填充字符通常与width
参数一起提供。 This indicates that if the value being formatted is smaller thanwidth
some extra characters will be printed around it.这表明如果格式化的值小于width
则会在其周围打印一些额外的字符。 The extra characters are specified byfill
, and the alignment can be one of the following options:额外的字符由fill
指定,对齐可以是以下选项之一:
<
- the argument is left-aligned inwidth
columns<
- 参数在width
列中左对齐^
- the argument is center-aligned inwidth
columns^
- 参数在width
列中居中对齐>
- the argument is right-aligned inwidth
columns>
- 参数在width
列中右对齐
assert_eq!("00000110", format!("{:0>8}", "110"));
// |||
// ||+-- width
// |+--- align
// +---- fill
See also:也可以看看:
As an alternative to Shepmaster's answer, if you are actually starting with a number rather than a string, and you want to display it as binary, the way to format that is:作为 Shepmaster 答案的替代方案,如果您实际上是从数字而不是字符串开始,并且希望将其显示为二进制,那么格式化的方法是:
let n: u32 = 0b11110000;
// 0 indicates pad with zeros
// 8 is the target width
// b indicates to format as binary
let formatted = format!("{:08b}", n);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.