PadLeft and PadRight Function

#define PADLEFT(source, tcount,ch)   Pad(source, tcount,ch,0)
#define PADRIGHT(source, tcount,ch)  Pad(source, tcount,ch,1)

/**************************************************
    INPUT:
            source: string to pag
            tcount: lenght of string
            ch    : char to pad
            mode  : 0 padleft otherwise padright
    RETURN:
            string with pad
***************************************************/
char* Pad(char *source,int tcount,char ch,char mode)
{
    char *d, *s;
    int npad,m,ns;

    ns=strlen(source);
    npad=tcount-ns;//number of char to pad

    if(!mode)//Implement Padleft
    {

        d=malloc(npad+ns);
        m=0;
        while(m<(ns+npad))
        {
            if (m<ns)
               d[m]=source[m];
            else//populate with ch
               d[m]=ch;
            m++;
        }
        d[m]=0;

    }
    else//Implement PadRight
    {
        d=malloc(npad);
        m=0;
        while(npad-->0)
        {
            d[m++]=ch;//create pad with ch
        }
        d[m]=0;
        memcpy(d+m,source,strlen(source));
        d[m+strlen(source)]=0;
    }

    return d;
}
void testPadleft()
{
   char s[30];
   char so[30];
   strcpy(s,"Hello");
   sprintf(so,"%s",PADLEFT(s,20,'_'));
   printf("\n[%s]",so);
   sprintf(so,"%s",PADRIGHT(s,20,'_'));
   printf("\n[%s]",so);
}
Advertisements