用左边的0填充字符串的最简单方法是什么?

问题描述 投票:12回答:2

填充字符串的最简单方法是将左侧的0填充为0

  • "110" = "00000110"
  • "11110000" = "11110000"

我曾尝试使用format!宏,但它只用空格填充到右边:

format!("{:08}", string);
rust formatting string-formatting number-formatting
2个回答
21
投票

fmt module documentation描述了所有格式选项:

Fill / Alignment

填充字符通常与width参数一起提供。这表示如果格式化的值小于width,则会在其周围打印一些额外的字符。额外的字符由fill指定,对齐可以是以下选项之一:

  • < - 参数在width列中左对齐
  • ^ - 参数在width专栏中居中对齐
  • > - 这个论点在width专栏中是正确的

assert_eq!("00000110", format!("{:0>8}", "110"));
//                                |||
//                                ||+-- width
//                                |+--- align
//                                +---- fill

也可以看看:


5
投票

作为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);
© www.soinside.com 2019 - 2024. All rights reserved.