rustHow to format string with padding in Rust
String padding in Rust can be done using the format!
macro. The format!
macro takes a format string and a list of arguments and returns a String
object. The format string can contain special formatting characters that will be replaced with the corresponding argument.
For example, to pad a string with spaces, the {:width$}
format can be used. The width
argument specifies the total width of the output string, and the $
character indicates that the padding should be done with spaces.
Code example:
let s = "Hello";
let padded = format!("{:10$}", s, 10);
println!("{}", padded);
Output
Hello
Explanation of code parts:
let s = "Hello";
- This line declares a variables
and assigns it the value"Hello"
.let padded = format!("{:10$}", s, 10);
- This line uses theformat!
macro to format the strings
with padding. The{:10$}
format indicates that the output string should have a total width of 10 characters, and the padding should be done with spaces.println!("{}", padded);
- This line prints the padded string to the console.
Helpful links:
More of Rust
- How to get a capture group using Rust regex?
- How to use Unicode in a regex in Rust?
- How to get the last element of a Rust slice?
- How to match the end of a line in a Rust regex?
- How to replace a capture group using Rust regex?
- How to use non-capturing groups in Rust regex?
- How to use an enum in a Rust HashMap?
- How to match whitespace with a regex in Rust?
- How to split a string with Rust regex?
- How to match a URL with a regex in Rust?
See more codes...