简体   繁体   English

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

[英]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 than width some extra characters will be printed around it.这表明如果格式化的值小于width则会在其周围打印一些额外的字符。 The extra characters are specified by fill , and the alignment can be one of the following options:额外的字符由fill指定,对齐可以是以下选项之一:

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

相关问题 在互斥锁上忽略中毒错误的最简单方法是什么? - What is the easiest way to ignore a poison error on Mutex? 什么是确定字符是否在Unicode范围内的最简单方法,在Rust中? - What is the easiest way to determine if a character is in Unicode range, in Rust? 检查SPI是否在STM32上正确初始化的最简单方法是什么? - What is the easiest way to check if SPI is correctly initialized on STM32? 如果可以失败,从stdin读取几个整数的最简单方法是什么? - What's the easiest way to read several ints from stdin if it's ok to fail? 使actix-web终结点处理程序的HTML输出正确呈现的最简单方法是什么? - What's the easiest way to get the HTML output of an actix-web endpoint handler to be rendered properly? 将 `&amp;str` 添加到 `String` 的最有效方法是什么? - What is the most efficient way to prepend a `&str` to a `String`? 将Vec打印为字符串的惯用方式是什么? - What is the idiomatic way to print a Vec as a string? 将字符串转换为 &amp;str 的惯用方法是什么? - What is the idiomatic way to convert a String to &str? 什么是 Rust 方法来调用需要来自 String 的字符串切片的方法 - What is the Rust way to call a method requireing a string slice from a String 从文字创建字符串的首选方法是什么? - What's the preferred way to create a String from a literal?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM