Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
813 views
in Technique[技术] by (71.8m points)

rust - 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

  • "110" = "00000110"

  • "11110000" = "11110000"

I have tried to use the format! macro but it only pads to the right with space:

format!("{:08}", string);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The 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 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:

  • < - 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

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...