logoalt Hacker News

TheTxTyesterday at 8:26 AM3 repliesview on HN

But how do you left pad a string?


Replies

1718627440yesterday at 10:52 AM

    char * 
    left_pad (const char * string, unsigned int pad)
    {
        char tmp[strlen (string)+pad+1];
        memset (tmp, ' ', pad);
        strcpy (tmp+pad, string);
        return strdup (tmp);
    } 
Doesn't sound too hard in my opinion. This only works for strings, that fit on the stack, so if you want to make it robust, you should check for the string size. It (like everything in C) can of course fail. Also it is a quite naive implementation, since it calculates the string size three times.
show 2 replies
kidminyesterday at 2:39 PM

snprintf(buf, bufsize, "%*s", padwidth, str)?