I wrote this function that\'s supposed to do StringPadRight(\"Hello\", 10, \"0\") -> \"Hello00000\".
char *StringPadRight(char *string, int padded_len, char
#include<stdio.h>
#include <string.h>
void padLeft(int length, char pad, char* inStr,char* outStr) {
int minLength = length * sizeof(char);
if (minLength < sizeof(outStr)) {
return;
}
int padLen = length - strlen(inStr);
padLen = padLen < 0 ? 0 : padLen;
memset(outStr, 0, sizeof(outStr));
memset(outStr, pad,padLen);
memcpy(outStr+padLen, inStr, minLength - padLen);
}
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]
You must make sure that the input string has enough space to hold all the padding characters. Try this:
char hello[11] = "Hello";
StringPadRight(hello, 10, "0");
Note that I allocated 11 bytes for the hello
string to account for the null terminator at the end.
It might be helpful to know that printf does padding for you, using %-10s as the format string will pad the input right in a field 10 characters long
printf("|%-10s|", "Hello");
will output
|Hello |
In this case the - symbol means "Left align", the 10 means "Ten characters in field" and the s means you are aligning a string.
Printf style formatting is available in many languages and has plenty of references on the web. Here is one of many pages explaining the formatting flags. As usual WikiPedia's printf page is of help too (mostly a history lesson of how widely printf has spread).