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

查看:25
本文介绍了用 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 一些额外的字符将被打印在它周围.多余的字符由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

另见:

这篇关于用 0 向左填充字符串的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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