Your Own Version of left-pad() – Solution

Can you write your own left-pad function in C? Would you get so angry that you’d pull it from the Jenga-tower NPM and bring the Internet to its knees? I hope your answer Yes to the first question and No to the second, because your task for this month’s Exercise is to write that function.

Adding spaces to the left side of a string is simple to code, though many potential solutions exist. If the program were just outputting the spaces and original string, it would be even easier. Alas, this solution requires that you create and return a new string from the leftpad() function. Here is my version:

char *leftpad(char *s, int width)
{
    int size,x;
    char *buffer;
    char *b;

    /* calculate the final string size */
    size = strlen(s) + width;
    
    /* allocate storage for the buffer */
    buffer = malloc( sizeof(char) * size + 1 );
    if( buffer==NULL )
    {
        fprintf(stderr,"Unable to allocate memory\n");
        exit(1);
    }

    /* pad the left end with spaces */
    b = buffer;
    for( x=0; x<width; x++ )
    {
        *b = ' ';
        b++;
    }

    /* append the string */
    strcpy(b,s);

    /* return the result */
    return(buffer);
}

I use char pointer buffer to hold the final string. Pointer b is an index that transfers the original string (argument s) into buffer.

First, storage is allocated for buffer. Its size is based on the original string’s length plus the width value, plus one for the null character. I use variable size to hold the string’s new length (minus the null character) just to make the code more readable.

Second, the buffer is padded with width number of spaces. A for loop uses the width value and variable b tracks the offset within buffer. The spaces are plopped into the newly created string.

Third, the strcpy() function copies the passed string s to the location set in variable b, which is within buffer. The strcopy() function handles terminating the string, which is ready to return to the caller, nicely padded.

You can click here to view my full solution. Here is sample output:

Pad  5 =      string
Pad 10 =           string
Pad  0 = string
Pad -3 = string
Pad  1 =  string

My solution’s approach is different from what is shown online in the NPM. Your’s may differ as well, given that multiple solutions exist for various programming puzzles. I hope that you met with success, and that you no longer have plans to take down the Internet.

Leave a Reply