A Rust utility that pads numbers in strings with leading zeros.
This utility takes an input string and a padding length, then returns a new string where all numbers in the original string are left-padded with zeros to reach the specified length. Numbers that are already at or above the specified length remain unchanged.
- Pads all whole numbers found in an input string with leading zeros
- Handles strings with multiple numbers
- Preserves non-numeric parts of the string
- Efficiently processes text using regular expressions
- Comprehensive test suite
This utility uses Rust's regex
crate to efficiently identify and process numbers within text:
- Pattern
\d+
matches one or more consecutive digits replace_all
function applies padding to each match- Zero-padding is implemented with Rust's format specifier
{:0>width$}
pad_numbers("James Bond 7", 3) -> "James Bond 007"
pad_numbers("PI=3.14", 2) -> "PI=03.14"
pad_numbers("It's 3:13pm", 2) -> "It's 03:13pm"
pad_numbers("It's 12:13pm", 2) -> "It's 12:13pm" (no padding needed)
pad_numbers("99UR1337", 6) -> "000099UR001337"
- O(n) where n is the length of the input string
- The regex engine scans the entire input string once to find all digit sequences
- Each matched number is processed in constant time for the padding operation
- The overall time complexity is dominated by the linear scan of the input string
- O(n) where n is the length of the input string
- In the worst case (all characters are digits that need padding), the resulting string could be substantially larger than the input
- The space required is proportional to the length of the input string plus any additional characters added through padding
- The regex engine itself requires a small constant amount of additional memory
Add this to your Cargo.toml
:
[dependencies]
spark-coding-challenge1 = { git = "https://github.com/yourusername/spark-coding-challenge1" }
# Build the project
cargo build
# Run the tests
cargo test
# Run with additional verbosity
cargo test --verbose
MIT