用 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
一些额外的字符将被打印在它周围.多余的字符由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
另见:
这篇关于用 0 向左填充字符串的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!