Challenge 14

🔳

Padding

Open in Code Editor or Copy Instructions
...solutions at bottom of page...

Often - either for output or because input is required in a specific format - we might want to 'pad' a string. This means adding additional characters, usually at the start (leading) or at the end (trailing)

For example, suppose we have the binary number 0111 (7), but want to represent this as 1 byte - we'd need to pad with 4 leading '0' characters to make it 00000111

Create a function padStart which takes the input string, the padding character and desired length of the string

Examples:

padStart("0111", "0", 8) would return "00000111"

padStart("abc", " ", 10) would return " abc" (7 spaces)

Extension:

Create a padEnd to add trailing characters and a padBoth which can pad both the start and end of a string

padEnd("Hello", "!", 3) would return "Hello!!!"

padBoth(" Welcome! ", "-", 5) would return "----- Welcome! -----"

Note: padStart & padEnd take the desired length of the returned string as a parameter, while padBoth takes the amount of extra padding to add a parameter. You are free to choose whatever functionality you want, or you could perhaps give it a convoluted, but more descriptive identifier - like "padBothWithNChars" or something

Feel free to modify the function signatures to allow padding with different characters at the start and end and also a different number of characters at the start and end

Solutions

IGCSE 0478 / O-Level 2210 A-Level 9618