patternrustCritical
What is the easiest way to pad a string with 0 to the left?
Viewed 0 times
witheasiestpadtheleftwaystringwhat
Problem
What is the easiest way to pad a string with 0 to the left so that
-
"110" = "00000110"
-
"11110000" = "11110000"
I have tried to use the
-
"110" = "00000110"
-
"11110000" = "11110000"
I have tried to use the
format! macro but it only pads to the right with space:format!("{:08}", string);Solution
The
Fill / Alignment
The fill character is provided normally in conjunction with the
smaller than
The extra characters are specified by
one of the following options:
See also:
fmt module documentation describes all the formatting options:Fill / Alignment
The fill character is provided normally in conjunction with the
width parameter. This indicates that if the value being formatted issmaller than
width some extra characters will be printed around it.The extra characters are specified by
fill, and the alignment can beone of the following options:
- ^
- the argument is center-aligned inwidthcolumns
- >
- the argument is right-aligned inwidth` columns
assert_eq!("00000110", format!("{:0>8}", "110"));
// |||
// ||+-- width
// |+--- align
// +---- fillSee also:
- 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
Code Snippets
assert_eq!("00000110", format!("{:0>8}", "110"));
// |||
// ||+-- width
// |+--- align
// +---- fillContext
Stack Overflow Q#50458144, score: 208
Revisions (0)
No revisions yet.