什么是最简单的方法来填充左侧的0的字符串? [英] What is the easiest way to pad a string with 0 to the left?

查看:206
本文介绍了什么是最简单的方法来填充左侧的0的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最简单的方法是在左侧填充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 than width some extra characters will be printed around it. The extra characters are specified by fill, and the alignment can be one of the following options:

  • <-参数在width列中左对齐
  • ^-参数在width列中居中对齐
  • >-参数在width列中右对齐
  • < - the argument is left-aligned in width columns
  • ^ - the argument is center-aligned in width columns
  • > - the argument is right-aligned in width 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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆