String Padding in C

前端 未结 10 1526
迷失自我
迷失自我 2020-11-28 22:25

I wrote this function that\'s supposed to do StringPadRight(\"Hello\", 10, \"0\") -> \"Hello00000\".

char *StringPadRight(char *string, int padded_len, char          


        
10条回答
  •  执笔经年
    2020-11-28 23:05

    For 'C' there is alternative (more complex) use of [s]printf that does not require any malloc() or pre-formatting, when custom padding is desired.

    The trick is to use '*' length specifiers (min and max) for %s, plus a string filled with your padding character to the maximum potential length.

    int targetStrLen = 10;           // Target output length  
    const char *myString="Monkey";   // String for output 
    const char *padding="#####################################################";
    
    int padLen = targetStrLen - strlen(myString); // Calc Padding length
    if(padLen < 0) padLen = 0;    // Avoid negative length
    
    printf("[%*.*s%s]", padLen, padLen, padding, myString);  // LEFT Padding 
    printf("[%s%*.*s]", myString, padLen, padLen, padding);  // RIGHT Padding 
    

    The "%*.*s" can be placed before OR after your "%s", depending desire for LEFT or RIGHT padding.

    [####Monkey] <-- Left padded, "%*.*s%s"
    [Monkey####] <-- Right padded, "%s%*.*s"

    I found that the PHP printf (here) does support the ability to give a custom padding character, using the single quote (') followed by your custom padding character, within the %s format.
    printf("[%'#10s]\n", $s); // use the custom padding character '#'
    produces:
    [####monkey]

提交回复
热议问题