Function pad_left::left_pad

source ·
pub fn left_pad(str: String, len: usize, ch: char) -> String
Expand description

Pads a string on the left with a specified character to reach a given length.

Arguments

  • str - The string to be padded.
  • len - The total length of the resulting string.
  • chr - The character used for padding.

Returns

A new String that is the padded string.

Examples

use pad_left::left_pad;

assert_eq!(left_pad("".to_string(), 0, ' '), "");
assert_eq!(left_pad("".to_string(), 10, ' '), "          ");
assert_eq!(left_pad("hello".to_string(), 5, ' '), "hello");
assert_eq!(left_pad("hello".to_string(), 10, ' '), "     hello");
assert_eq!(left_pad("hello".to_string(), 10, '*'), "*****hello");
assert_eq!(left_pad("".to_string(), 10, ' '), "          ".to_string());
assert_eq!(left_pad("hello".to_string(), 0, ' '), "hello".to_string());
assert_eq!(left_pad("hello".to_string(), 5, ' '), "hello".to_string());
assert_eq!(left_pad("hello".to_string(), 10, ' '), "     hello".to_string());
assert_eq!(left_pad("hello".to_string(), 15, ' '), "          hello".to_string());
assert_eq!(left_pad("hello".to_string(), 10, '\0'), "     hello".to_string());
assert_eq!(left_pad("hello".to_string(), 15, '\0'), "          hello".to_string());
assert_eq!(left_pad("hello".to_string(), 10, '-'), "-----hello".to_string());
assert_eq!(left_pad("hello".to_string(), 15, '-'), "----------hello".to_string());
assert_eq!(left_pad("hello".to_string(), 10, '🚀'), "🚀🚀🚀🚀🚀hello".to_string());
assert_eq!(left_pad("hello".to_string(), 15, '🚀'), "🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀hello".to_string());

Complexity

Time complexity

O(log(n)), where n is the length difference between the input string and the desired length.

Space complexity

O(log(n)), where n is the length difference between the input string and the desired length, since we are constructing a new string with the padded characters. However, the actual space used may be less than this if the ch parameter is a space character and the length difference is less than 20, in which case we construct a pre-allocated string instead of dynamically creating one.